text:
/*
 * author : younger.shen
 * email  : younger.x.shen@gmail.com
 */

/*
 *the util module file
 *contains some kind of util method
 *Dependences : none
 */

 (function(window){

    var HUtils = {}
    if(!window.HUtils){

        window.HUtils = HUtils;
    }

    HUtils.objectConfig = function(sourceObject, attrs){

        for(var i in attrs){

            if(sourceObject[i] != "undefined"){
                sourceObject[i] = attrs[i];
            }
        }
    }

 })(window);

redpajama_set_name: RedPajamaGithub


text:
/**
* Tae Won Ha — @hataewon
*
* http://taewon.de
* http://qvacua.com
*
* See LICENSE
*/

#import "NSString+QVWorkspace.h"

@implementation NSString (QVWorkspace)

- (void)drawAtBasePoint:(CGPoint)base angle:(CGFloat)radian attributes:(NSDictionary *)attr {
  CGSize textSize = [self sizeWithAttributes:attr];

  NSAffineTransform *translation = [[NSAffineTransform alloc] init];
  [translation translateXBy:base.x yBy:base.y];
  NSAffineTransform *rotation = [[NSAffineTransform alloc] init];
  [rotation rotateByRadians:radian];

  [translation concat];
  [rotation concat];

  [self drawAtPoint:CGPointMake(-1 * textSize.width / 2, -1 * textSize.height / 2) withAttributes:attr];

  [rotation invert];
  [translation invert];

  [rotation concat];
  [translation concat];
}

@end


text:
layout: relation
title: 'det'
shortdef: 'determiner'
---

The relation determiner (det) holds between a nominal head and its determiner.

~~~ sdparse
Bütün kitapları okudu . \n (He\/she) have read all books
det(kitapları, Bütün)
~~~

~~~ sdparse
Güzel bir kitap okudum . \n I read a nice book
det(kitap, bir)
amod(kitap, Güzel)
~~~

~~~ sdparse
Bu kitabı okumalısın . \n You should read this book
det(kitabı, Bu)
~~~

~~~ sdparse
Bazı kitaplar bombadan tehlikelidir . \n Some books are more dangerous than a bomb
det(kitaplar, Bazı)
~~~


text:
Upgrade in progress!

Is writeable(by server)

Download update

21313

21313

21313

Extracting

Database migration

        Noclayer detected new upgrade on disk!

        Hit button to migrate database

Please be patient!

Download update manual!

Download

Backup database first!

Migrate Database

Upgrade finished!

Reload Noclayer


text:
package org.xsystem.bpmn2.model.foundation;

import org.xsystem.bpmn2.model.system.DefinitionElement;
import org.xsystem.bpmn2.model.system.Reference;

/**
 *
 * @author Andrey Timofeev
 */
public interface BaseElement extends DefinitionElement{
    public String getId();

    public void setId(String id);

    public String TypeName();

    public Object getExtensionElements();

    public void   setExtensionElements(Object extensionElements);

    public default Reference getReference() {
       Reference ref= getOwnerDefinitions().createReference(getId());
       return ref;
    }
}


text:
<?php

namespace PHPSQLParser\Test\Parser;
use PHPSQLParser\PHPSQLParser;
use PHPSQLParser\PHPSQLCreator;

class issue45Test extends \PHPUnit\Framework\TestCase {

    public function testIssue45() {

        $parser = new PHPSQLParser();

        $sql = 'SELECT a from b left join c on c.a = b.a and (c.b. = b.b) where a.a > 1';
        $parser->parse($sql, true);
        $p = $parser->parsed;
        $expected = getExpectedValue(dirname(__FILE__), 'issue45.serialized');
        $this->assertEquals($expected, $p, 'issue 45 position problem');

    }
}


text:
package org.popper.inttest.pos;

import org.popper.fw.jemmy.annotations.Dialog;
import org.popper.fw.jemmy.annotations.Frame;
import org.popper.fw.jemmy.annotations.locator.Locator;
import org.popper.fw.jemmy.annotations.locator.Window;
import org.popper.fw.jemmy.elements.IJemmyButton;
import org.popper.fw.jemmy.elements.IJemmyLabel;

@Frame
@Locator(title = "Example App")
public interface AppWithModalSubwindowPo {
    @Locator(xpath = "//*[@id='openSub']")
    IJemmyButton openSubButton();

    @Window
    @Locator(title = "Sub")
    Sub subWindow();

    @Dialog
    @Locator(title = "Sub")
    public static interface Sub {
        @Locator(xpath = "//*[@id='openSubSub']")
        IJemmyButton openSubSubButton();

        @Locator(xpath = "//*[@id='dialogLabel']")
        IJemmyLabel label();

        @Window
        @Locator(title = "SubSub")
        SubSub subSubwindow();
    }

    @Dialog
    @Locator(title = "SubSub")
    public static interface SubSub {
        @Locator(xpath = "//*[@id='dialogLabel']")
        IJemmyLabel label();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Jørgensen, N. Z. Jl Bot. 37(2): 262 (1999)

#### Original name
Parmeliella aggregata P.M. Jørg. & D.J. Galloway

### Remarks
null


text:
import serial
import struct

import sys, getopt, time, glob#, traceback

from mtdef import MID, OutputMode, OutputSettings, MTException, Baudrates

################################################################
# MTDevice class
################################################################
## XSens MT device communication object.
class MTDevice(object):
	"""XSens MT device communication object."""

	def __init__(self, port, baudrate=115200, timeout=0.1, autoconf=True,
			config_mode=False):
		"""Open device."""
		## serial interface to the device
		self.device = serial.Serial(port, baudrate, timeout=timeout,
				writeTimeout=timeout)
		self.device.flushInput()	# flush to make sure the port is ready TODO
		self.device.flushOutput()	# flush to make sure the port is ready TODO
		## timeout for communication
		self.timeout = timeout
		if autoconf:
			self.auto_config()
		else:
			## mode parameter of the IMU
			self.mode = None
			## settings parameter of the IMU
			self.settings = None
			## length of the MTData message
			self.length = None
			## header of the MTData message
			self.header = None
		if config_mode:
			self.GoToConfig()

	############################################################
	# Low-level communication
	############################################################

	## Low-level message sending function.
	def write_msg(self, mid, data=[]):
		"""Low-level message sending function."""
		length = len(data)
		if length>254:
			lendat = [0xFF, 0xFF&length, 0xFF&(length>>8)]
		else:
			lendat = [length]
		packet = [0xFA, 0xFF, mid] + lendat + list(data)
		packet.append(0xFF&(-(sum(packet[1:]))))
		msg = struct.pack('%dB'%len(packet), *packet)
		self.device.write(msg)
#		print "MT: Write message id 0x%02X with %d data bytes: [%s]"%(mid,length,
#				' '.join("%02X"% v for v in data))
		#self.device.flush() #TODO evaluate

	## Low-level MTData receiving function.
	# Take advantage of known message length.
	def read_data_msg(self, buf=bytearray()):
		"""Low-level MTData receiving function.
		Take advantage of known message length."""
		start = time.time()
		if self.length>254:
			totlength = 7 + self.length
		else:
			totlength = 5 + self.length
		while (time.time()-start)<self.timeout:
			buf.extend(self.device.read(totlength-len(buf)))
			preamble_ind = buf.find(self.header)
			if preamble_ind==-1:	# not found
				# discard unexploitable data
				del buf[:-3]
				continue
			elif preamble_ind:	# found but not at start
				# discard leading bytes
				del buf[:preamble_ind]
				# complete message for checksum
				buf.extend(self.device.read(totlength-len(buf)))
			if 0xFF&sum(buf[1:]):
				#sys.stderr.write("MT: invalid checksum; discarding data and "\
				#		"waiting for next message.\n")
				del buf[:buf.find(self.header)-2]
				continue
			data = str(buf[-self.length-1:-1])
			del buf[:]
			return data
		else:
			raise MTException("could not find MTData message.")

	## Low-level message receiving function.
	def read_msg(self):
		"""Low-level message receiving function."""
		start = time.time()
		while (time.time()-start)<self.timeout:
			# read first char of preamble
			c = self.device.read()
			if not c:
				raise MTException("timeout waiting for message.")
			if ord(c)<>0xFA:
				continue
			# second part of preamble
			if ord(self.device.read())<>0xFF:	# we assume no timeout anymore
				continue
			# read message id and length of message
			mid, length = struct.unpack('!BB', self.device.read(2))
			if length==255:	# extended length
				length, = struct.unpack('!H', self.device.read(2))
			# read contents and checksum
			buf = self.device.read(length+1)
			checksum = ord(buf[-1])
			data = struct.unpack('!%dB'%length, buf[:-1])
			if mid == MID.Error:
				sys.stderr.write("MT error 0x%02X: %s."%(data[0],
						MID.ErrorCodes[data[0]]))
#			print "MT: Got message id 0x%02X with %d data bytes: [%s]"%(mid,length,
#					' '.join("%02X"% v for v in data))
			if 0xFF&sum(data, 0xFF+mid+length+checksum):
				sys.stderr.write("invalid checksum; discarding data and "\
						"waiting for next message.")
				continue
			return (mid, buf[:-1])
		else:
			raise MTException("could not find message.")

	## Send a message and read confirmation
	def write_ack(self, mid, data=[]):
		"""Send a message a read confirmation."""
		self.write_msg(mid, data)
		for tries in range(10):
			mid_ack, data_ack = self.read_msg()
			if mid_ack==(mid+1):
				break
		else:
			raise MTException("Ack (0x%X) expected, MID 0x%X received instead"\
					" (after 10 tries)."%(mid+1, mid_ack))
		return data_ack

	############################################################
	# High-level functions
	############################################################
	## Reset MT device.
	def Reset(self):
		"""Reset MT device."""
		self.write_ack(MID.Reset)

	## Place MT device in configuration mode.
	def GoToConfig(self):
		"""Place MT device in configuration mode."""
		self.write_ack(MID.GoToConfig)

	## Place MT device in measurement mode.
	def GoToMeasurement(self):
		"""Place MT device in measurement mode."""
		self.write_ack(MID.GoToMeasurement)

	## Restore MT device configuration to factory defaults (soft version).
	def RestoreFactoryDefaults(self):
		"""Restore MT device configuration to factory defaults (soft version).
		"""
		self.GoToConfig()
		self.write_ack(MID.RestoreFactoryDef)

	## Get current output mode.
	# Assume the device is in Config state.
	def GetOutputMode(self):
		"""Get current output mode.
		Assume the device is in Config state."""
		data = self.write_ack(MID.SetOutputMode)
		self.mode, = struct.unpack('!H', data)
		return self.mode

	## Select which information to output.
	# Assume the device is in Config state.
	def SetOutputMode(self, mode):
		"""Select which information to output.
		Assume the device is in Config state."""
		H, L = (mode&0xFF00)>>8, mode&0x00FF
		self.write_ack(MID.SetOutputMode, (H, L))

	## Get current output mode.
	# Assume the device is in Config state.
	def GetOutputSettings(self):
		"""Get current output mode.
		Assume the device is in Config state."""
		data = self.write_ack(MID.SetOutputSettings)
		self.settings, = struct.unpack('!I', data)
		return self.settings

	## Select how to output the information.
	# Assume the device is in Config state.
	def SetOutputSettings(self, settings):
		"""Select how to output the information.
		Assume the device is in Config state."""
		HH, HL = (settings&0xFF000000)>>24, (settings&0x00FF0000)>>16
		LH, LL = (settings&0x0000FF00)>>8, settings&0x000000FF
		self.write_ack(MID.SetOutputSettings, (HH, HL, LH, LL))

	## Set the period of sampling.
	# Assume the device is in Config state.
	def SetPeriod(self, period):
		"""Set the period of sampling.
		Assume the device is in Config state."""
		H, L = (period&0xFF00)>>8, period&0x00FF
		self.write_ack(MID.SetPeriod, (H, L))

	## Set the output skip factor.
	# Assume the device is in Config state.
	def SetOutputSkipFactor(self, skipfactor):
		"""Set the output skip factor.
		Assume the device is in Config state."""
		H, L = (skipfactor&0xFF00)>>8, skipfactor&0x00FF
		self.write_ack(MID.SetOutpuSkipFactor, (H, L))

	## Get data length.
	# Assume the device is in Config state.
	def ReqDataLength(self):
		"""Get data length.
		Assume the device is in Config state."""
		data = self.write_ack(MID.ReqDataLength)
		self.length, = struct.unpack('!H', data)
		self.header = '\xFA\xFF\x32'+chr(self.length)
		return self.length

	## Ask for the current configuration of the MT device.
	# Assume the device is in Config state.
	def ReqConfiguration(self):
		"""Ask for the current configuration of the MT device.
		Assume the device is in Config state."""
		config = self.write_ack(MID.ReqConfiguration)
		try:
			masterID, period, skipfactor, _, _, _, date, time, num, deviceID,\
					length, mode, settings =\
					struct.unpack('!IHHHHI8s8s32x32xHIHHI8x', config)
		except struct.error:
			raise MTException("could not parse configuration.")
		self.mode = mode
		self.settings = settings
		self.length = length
		self.header = '\xFA\xFF\x32'+chr(length)
		conf = {'output-mode': mode,
				'output-settings': settings,
				'length': length,
				'period': period,
				'skipfactor': skipfactor,
				'Master device ID': masterID,
				'date': date,
				'time': time,
				'number of devices': num,
				'device ID': deviceID}
		return conf

	## Set the baudrate of the device using the baudrate id.
	# Assume the device is in Config state.
	def SetBaudrate(self, brid):
		"""Set the baudrate of the device using the baudrate id.
		Assume the device is in Config state."""
		self.write_ack(MID.SetBaudrate, (brid,))

	## Request the available XKF scenarios on the device.
	# Assume the device is in Config state.
	def ReqAvailableScenarios(self):
		"""Request the available XKF scenarios on the device.
		Assume the device is in Config state."""
		scenarios_dat = self.write_ack(MID.ReqAvailableScenarios)
		scenarios = []
		try:
			for i in range(len(scenarios_dat)/22):
				scenario_type, version, label =\
						struct.unpack('!BB20s', scenarios_dat[22*i:22*(i+1)])
				scenarios.append((scenario_type, version, label.strip()))
			## available XKF scenarios
			self.scenarios = scenarios
		except struct.error:
			raise MTException("could not parse the available XKF scenarios.")
		return scenarios

	## Request the ID of the currently used XKF scenario.
	# Assume the device is in Config state.
	def ReqCurrentScenario(self):
		"""Request the ID of the currently used XKF scenario.
		Assume the device is in Config state."""
		data = self.write_ack(MID.ReqCurrentScenario)
		## current XKF id
		self.scenario_id, = struct.unpack('!H', data)
		try:
			scenarios = self.scenarios
		except AttributeError:
			scenarios = self.ReqAvailableScenarios()
		for t, _, label in scenarios:
			if t==self.scenario_id:
				## current XKF label
				self.scenario_label = label
				break
		else:
			self.scenario_label = ""
		return self.scenario_id, self.scenario_label

	## Sets the XKF scenario to use.
	# Assume the device is in Config state.
	def SetCurrentScenario(self, scenario_id):
		"""Sets the XKF scenario to use.
		Assume the device is in Config state."""
		self.write_ack(MID.SetCurrentScenario, (0x00, scenario_id&0xFF))

	############################################################
	# High-level utility functions
	############################################################
	## Configure the mode and settings of the MT device.
	def configure(self, mode, settings, period=None, skipfactor=None):
		"""Configure the mode and settings of the MT device."""
		self.GoToConfig()
		self.SetOutputMode(mode)
		self.SetOutputSettings(settings)
		if period:
			self.SetPeriod(period)
		if skipfactor:
			self.SetOutputSkipFactor(skipfactor)

		self.GetOutputMode()
		self.GetOutputSettings()
		self.ReqDataLength()
		self.GoToMeasurement()

	## Read configuration from device.
	def auto_config(self):
		"""Read configuration from device."""
		self.GoToConfig()
		mode = self.GetOutputMode()
		settings = self.GetOutputSettings()
		length = self.ReqDataLength()
		self.GoToMeasurement()
		return mode, settings, length

	## Read and parse a measurement packet
	def read_measurement(self, mode=None, settings=None):
		"""Read and parse a measurement packet."""
		# getting mode
		if mode is None:
			mode = self.mode
		if settings is None:
			settings = self.settings
		# getting data
		data = self.read_data_msg()
		#_, data = self.read_msg()
		# data object
		output = {}
		try:
			# raw IMU first
			if mode & OutputMode.RAW:
				o = {}
				o['accX'], o['accY'], o['accZ'], o['gyrX'], o['gyrY'], o['gyrZ'],\
						o['magX'], o['magY'], o['magZ'], o['temp'] =\
						struct.unpack('!10H', data[:20])
				data = data[20:]
				output['RAW'] = o
			# raw GPS second
			if mode & OutputMode.RAWGPS:
				o = {}
				o['Press'], o['bPrs'], o['ITOW'], o['LAT'], o['LON'], o['ALT'],\
						o['VEL_N'], o['VEL_E'], o['VEL_D'], o['Hacc'], o['Vacc'],\
						o['Sacc'], o['bGPS'] = struct.unpack('!HBI6i3IB', data[:44])
				data = data[44:]
				output['RAWGPS'] = o
			# temperature
			if mode & OutputMode.Temp:
				temp, = struct.unpack('!f', data[:4])
				data = data[4:]
				output['Temp'] = temp
			# calibrated data
			if mode & OutputMode.Calib:
				o = {}
				if not (settings&OutputSettings.CalibMode_GyrMag):
					o['accX'], o['accY'], o['accZ'] = struct.unpack('!3f',\
							 data[:12])
					data = data[12:]
				if not (settings&OutputSettings.CalibMode_AccMag):
					o['gyrX'], o['gyrY'], o['gyrZ'] = struct.unpack('!3f',\
							 data[:12])
					data = data[12:]
				if not (settings&OutputSettings.CalibMode_AccGyr):
					o['magX'], o['magY'], o['magZ'] = struct.unpack('!3f',\
							 data[:12])
					data = data[12:]
				output['Calib'] = o
			# orientation
			if mode & OutputMode.Orient:
				o = {}
				if settings & OutputSettings.OrientMode_Euler:
					o['roll'], o['pitch'], o['yaw'] = struct.unpack('!3f', data[:12])
					data = data[12:]
				elif settings & OutputSettings.OrientMode_Matrix:
					a, b, c, d, e, f, g, h, i = struct.unpack('!9f', data[:36])
					data = data[36:]
					o['matrix'] = ((a, b, c), (d, e, f), (g, h, i))
				else: # OutputSettings.OrientMode_Quaternion:
					q0, q1, q2, q3 = struct.unpack('!4f', data[:16])
					data = data[16:]
					o['quaternion'] = (q0, q1, q2, q3)
				output['Orient'] = o
			# auxiliary
			if mode & OutputMode.Auxiliary:
				o = {}
				if not (settings&OutputSettings.AuxiliaryMode_NoAIN1):
					o['Ain_1'], = struct.unpack('!H', data[:2])
					data = data[2:]
				if not (settings&OutputSettings.AuxiliaryMode_NoAIN2):
					o['Ain_2'], = struct.unpack('!H', data[:2])
					data = data[2:]
				output['Auxiliary'] = o
			# position
			if mode & OutputMode.Position:
				o = {}
				o['Lat'], o['Lon'], o['Alt'] = struct.unpack('!3f', data[:12])
				data = data[12:]
				output['Position'] = o
			# velocity
			if mode & OutputMode.Velocity:
				o = {}
				o['Vel_X'], o['Vel_Y'], o['Vel_Z'] = struct.unpack('!3f', data[:12])
				data = data[12:]
				output['Velocity'] = o
			# status
			if mode & OutputMode.Status:
				status, = struct.unpack('!B', data[:1])
				data = data[1:]
				output['Status'] = status
			# sample counter
			if settings & OutputSettings.Timestamp_SampleCnt:
				TS, = struct.unpack('!H', data[:2])
				data = data[2:]
				output['Sample'] = TS
		except struct.error, e:
			raise MTException("could not parse MTData message.")
		if data <> '':
			raise MTException("could not parse MTData message (too long).")
		return output

	## Change the baudrate, reset the device and reopen communication.
	def ChangeBaudrate(self, baudrate):
		"""Change the baudrate, reset the device and reopen communication."""
		self.GoToConfig()
		brid = Baudrates.get_BRID(baudrate)
		self.SetBaudrate(brid)
		self.Reset()
		#self.device.flush()
		self.device.baudrate=baudrate
		#self.device.flush()
		time.sleep(0.01)
		self.read_msg()
		self.write_msg(0x3f)

################################################################
# Auto detect port
################################################################
def find_devices():
	mtdev_list = []
	for port in glob.glob("/dev/tty*S*"):
		try:
			br = find_baudrate(port)
			if br:
				mtdev_list.append((port, br))
		except MTException:
			pass
	return mtdev_list

################################################################
# Auto detect baudrate
################################################################
def find_baudrate(port):
	baudrates = (115200, 460800, 921600, 230400, 57600, 38400, 19200, 9600)
	for br in baudrates:
		try:
			mt = MTDevice(port, br)
		except serial.SerialException:
			raise MTException("unable to open %s"%port)
		try:
			mt.GoToConfig()
			mt.GoToMeasurement()
			return br
		except MTException:
			pass

################################################################
# Documentation for stand alone usage
################################################################
def usage():
		print """MT device driver.
Usage:
	./mtdevice.py [commands] [opts]

Commands:
	-h, --help
		Print this help and quit.
	-r, --reset
		Reset device to factory defaults.
	-a, --change-baudrate=NEW_BAUD
		Change baudrate from BAUD (see below) to NEW_BAUD.
	-c, --configure
		Configure the device (needs MODE and SETTINGS arguments below).
	-e, --echo
		Print MTData. It is the default if no other command is supplied.
	-i, --inspect
		Print current MT device configuration.
	-x, --xkf-scenario=ID
		Change the current XKF scenario.

Options:
	-d, --device=DEV
		Serial interface of the device (default: /dev/ttyUSB0). If 'auto', then
		all serial ports are tested at all baudrates and the first
		suitable device is used.
	-b, --baudrate=BAUD
		Baudrate of serial interface (default: 115200). If 0, then all
		rates are tried until a suitable one is found.
	-m, --output-mode=MODE
		Mode of the device selecting the information to output.
		This is required for 'configure' command. If it is not present
		in 'echo' command, the configuration will be read from the
		device.
		MODE can be either the mode value in hexadecimal, decimal or
		binary form, or a string composed of the following characters
		(in any order):
			t	temperature, [0x0001]
			c	calibrated data, [0x0002]
			o	orientation data, [0x0004]
			a	auxiliary data, [0x0008]
			p	position data (requires MTi-G), [0x0010]
			v	velocity data (requires MTi-G), [0x0020]
			s	status data, [0x0800]
			g	raw GPS mode (requires MTi-G), [0x1000]
			r	raw (incompatible with others except raw GPS),
				[0x4000]
		For example, use "--output-mode=so" to have status and
		orientation data.
	-s, --output-settings=SETTINGS
		Settings of the device.
		This is required for 'configure' command. If it is not present
		in 'echo' command, the configuration will be read from the
		device.
		SETTINGS can be either the settings value in hexadecimal,
		decimal or binary form, or a string composed of the following
		characters (in any order):
			t	sample count (excludes 'n')
			n	no sample count (excludes 't')
			q	orientation in quaternion (excludes 'e' and 'm')
			e	orientation in Euler angles (excludes 'm' and
				'q')
			m	orientation in matrix (excludes 'q' and 'e')
			A	acceleration in calibrated data
			G	rate of turn in calibrated data
			M	magnetic field in calibrated data
			i	only analog input 1 (excludes 'j')
			j	only analog input 2 (excludes 'i')
			N	North-East-Down instead of default: X North Z up
		For example, use "--output-settings=tqMAG" for all calibrated
		data, sample counter and orientation in quaternion.
	-p, --period=PERIOD
		Sampling period in (1/115200) seconds (default: 1152).
		Minimum is 225 (1.95 ms, 512 Hz), maximum is 1152
		(10.0 ms, 100 Hz).
		Note that it is the period at which sampling occurs, not the
		period at which messages are sent (see below).
	-f, --skip-factor=SKIPFACTOR
		Number of samples to skip before sending MTData message
		(default: 0).
		The frequency at which MTData message is send is:
			115200/(PERIOD * (SKIPFACTOR + 1))
		If the value is 0xffff, no data is send unless a ReqData request
		is made.
"""

################################################################
# Main function
################################################################
def main():
	# parse command line
	shopts = 'hra:ceid:b:m:s:p:f:x:'
	lopts = ['help', 'reset', 'change-baudrate=', 'configure', 'echo',
			'inspect', 'device=', 'baudrate=', 'output-mode=',
			'output-settings=', 'period=', 'skip-factor=', 'xkf-scenario=']
	try:
		opts, args = getopt.gnu_getopt(sys.argv[1:], shopts, lopts)
	except getopt.GetoptError, e:
		print e
		usage()
		return 1
	# default values
	device = '/dev/ttyUSB0'
	baudrate = 115200
	mode = None
	settings = None
	period = None
	skipfactor = None
	new_baudrate = None
	new_xkf = None
	actions = []
	# filling in arguments
	for o, a in opts:
		if o in ('-h', '--help'):
			usage()
			return
		if o in ('-r', '--reset'):
			actions.append('reset')
		if o in ('-a', '--change-baudrate'):
			try:
				new_baudrate = int(a)
			except ValueError:
				print "change-baudrate argument must be integer."
				return 1
			actions.append('change-baudrate')
		if o in ('-c', '--configure'):
			actions.append('configure')
		if o in ('-e', '--echo'):
			actions.append('echo')
		if o in ('-i', '--inspect'):
			actions.append('inspect')
		if o in ('-x', '--xkf-scenario'):
			try:
				new_xkf = int(a)
			except ValueError:
				print "xkf-scenario argument must be integer."
				return 1
			actions.append('xkf-scenario')
		if o in ('-d', '--device'):
			device = a
		if o in ('-b', '--baudrate'):
			try:
				baudrate = int(a)
			except ValueError:
				print "baudrate argument must be integer."
				return 1
		if o in ('-m', '--output-mode'):
			mode = get_mode(a)
			if mode is None:
				return 1
		if o in ('-s', '--output-settings'):
			settings = get_settings(a)
			if settings is None:
				return 1
		if o in ('-p', '--period'):
			try:
				period = int(a)
			except ValueError:
				print "period argument must be integer."
				return 1
		if o in ('-f', '--skip-factor'):
			try:
				skipfactor = int(a)
			except ValueError:
				print "skip-factor argument must be integer."
				return 1
	# if nothing else: echo
	if len(actions) == 0:
		actions.append('echo')
	try:
		if device=='auto':
			devs = find_devices()
			if devs:
				print "Detected devices:","".join('\n\t%s @ %d'%(d,p) for d,p in
						devs)
				print "Using %s @ %d"%devs[0]
				device, baudrate = devs[0]
			else:
				print "No suitable device found."
				return 1
		# find baudrate
		if not baudrate:
			baudrate = find_baudrate(device)
		if not baudrate:
			print "No suitable baudrate found."
			return 1
		# open device
		try:
			mt = MTDevice(device, baudrate)
		except serial.SerialException:
			raise MTException("unable to open %s"%device)
		# execute actions
		if 'inspect' in actions:
			mt.GoToConfig()
			print "Device: %s at %d Bd:"%(device, baudrate)
			print "General configuration:", mt.ReqConfiguration()
			print "Available scenarios:", mt.ReqAvailableScenarios()
			print "Current scenario: %s (id: %d)"%mt.ReqCurrentScenario()[::-1]
			mt.GoToMeasurement()
		if 'change-baudrate' in actions:
			print "Changing baudrate from %d to %d:"%(baudrate, new_baudrate),
			sys.stdout.flush()
			mt.ChangeBaudrate(new_baudrate)
			print " Ok"		# should we test it was actually ok?
		if 'reset' in actions:
			print "Restoring factory defaults",
			sys.stdout.flush()
			mt.RestoreFactoryDefaults()
			print " Ok"		# should we test it was actually ok?
		if 'configure' in actions:
			if mode is None:
				print "output-mode is require to configure the device."
				return 1
			if settings is None:
				print "output-settings is required to configure the device."
				return 1
			print "Configuring mode and settings",
			sys.stdout.flush()
			mt.configure(mode, settings, period, skipfactor)
			print " Ok"		# should we test it was actually ok?
		if 'xkf-scenario' in actions:
			print "Changing XKF scenario",
			sys.stdout.flush()
			mt.GoToConfig()
			mt.SetCurrentScenario(new_xkf)
			mt.GoToMeasurement()
			print "Ok"
		if 'echo' in actions:
#			if (mode is None) or (settings is None):
#				mode, settings, length = mt.auto_config()
#				print mode, settings, length
			try:
				while True:
					print mt.read_measurement(mode, settings)
			except KeyboardInterrupt:
				pass
	except MTException as e:
		#traceback.print_tb(sys.exc_info()[2])
		print e

def get_mode(arg):
	"""Parse command line output-mode argument."""
	try:	# decimal
		mode = int(arg)
		return mode
	except ValueError:
		pass
	if arg[0]=='0':
		try:	# binary
			mode = int(arg, 2)
			return mode
		except ValueError:
			pass
		try:	# hexadecimal
			mode = int(arg, 16)
			return mode
		except ValueError:
			pass
	# string mode specification
	mode = 0
	for c in arg:
		if c=='t':
			mode |= OutputMode.Temp
		elif c=='c':
			mode |= OutputMode.Calib
		elif c=='o':
			mode |= OutputMode.Orient
		elif c=='a':
			mode |= OutputMode.Auxiliary
		elif c=='p':
			mode |= OutputMode.Position
		elif c=='v':
			mode |= OutputMode.Velocity
		elif c=='s':
			mode |= OutputMode.Status
		elif c=='g':
			mode |= OutputMode.RAWGPS
		elif c=='r':
			mode |= OutputMode.RAW
		else:
			print "Unknown output-mode specifier: '%s'"%c
			return
	return mode

def get_settings(arg):
	"""Parse command line output-settings argument."""
	try:	# decimal
		settings = int(arg)
		return settings
	except ValueError:
		pass
	if arg[0]=='0':
		try:	# binary
			settings = int(arg, 2)
			return settings
		except ValueError:
			pass
		try:	# hexadecimal
			settings = int(arg, 16)
			return settings
		except ValueError:
			pass
	# strings settings specification
	timestamp = 0
	orient_mode = 0
	calib_mode = OutputSettings.CalibMode_Mask
	NED = 0
	for c in arg:
		if c=='t':
			timestamp = OutputSettings.Timestamp_SampleCnt
		elif c=='n':
			timestamp = OutputSettings.Timestamp_None
		elif c=='q':
			orient_mode = OutputSettings.OrientMode_Quaternion
		elif c=='e':
			orient_mode = OutputSettings.OrientMode_Euler
		elif c=='m':
			orient_mode = OutputSettings.OrientMode_Matrix
		elif c=='A':
			calib_mode &= OutputSettings.CalibMode_Acc
		elif c=='G':
			calib_mode &= OutputSettings.CalibMode_Gyr
		elif c=='M':
			calib_mode &= OutputSettings.CalibMode_Mag
		elif c=='i':
			calib_mode &= OutputSettings.AuxiliaryMode_NoAIN2
		elif c=='j':
			calib_mode &= OutputSettings.AuxiliaryMode_NoAIN1
		elif c=='N':
			NED = OutputSettings.Coordinates_NED
		else:
			print "Unknown output-settings specifier: '%s'"%c
			return
	settings = timestamp|orient_mode|calib_mode|NED
	return settings

if __name__=='__main__':
	main()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>../libs/three/src/loaders/MaterialLoader.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for:

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

AbstractPlugin

Config

Controls

Plot

Plugin 3D

Plugin Axes

Plugin BasicMaterial

Plugin CameraControl

Plugin Color

Plugin Dataset

Plugin File

Plugin Function

Plugin Heatmap

Plugin Light

Plugin LinePlot

Plugin Plane

Plugin ScatterPlot

Plugin SurfacePlot

Plugin WireframeMaterial

SceneGraph

Templates

Toolbox

UTILS

VLib

VMediator

Controls

main

Plot

SceneGraph

Templates

Toolbox

VLib

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: ../libs/three/src/loaders/MaterialLoader.js

/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.MaterialLoader = function ( manager ) {

	this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;

};

THREE.MaterialLoader.prototype = {

	constructor: THREE.MaterialLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var loader = new THREE.XHRLoader();
		loader.setCrossOrigin( this.crossOrigin );
		loader.load( url, function ( text ) {

			onLoad( scope.parse( JSON.parse( text ) ) );

		} );

	},

	setCrossOrigin: function ( value ) {

		this.crossOrigin = value;

	},

	parse: function ( json ) {

		var material = new THREE[ json.type ];

		if ( json.color !== undefined ) material.color.setHex( json.color );
		if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
		if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
		if ( json.specular !== undefined ) material.specular.setHex( json.specular );
		if ( json.shininess !== undefined ) material.shininess = json.shininess;
		if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
		if ( json.blending !== undefined ) material.blending = json.blending;
		if ( json.side !== undefined ) material.side = json.side;
		if ( json.opacity !== undefined ) material.opacity = json.opacity;
		if ( json.transparent !== undefined ) material.transparent = json.transparent;
		if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;

		if ( json.materials !== undefined ) {

			for ( var i = 0, l = json.materials.length; i < l; i ++ ) {

				material.materials.push( this.parse( json.materials[ i ] ) );

			}

		}

		return material;

	}

};


text:
<?hh // strict

namespace tomzx\HackBot\Responders\Commands;

use Arry\Arry;
use tomzx\HackBot\Adapters\IRC;
use tomzx\HackBot\Core\Dispatcher;
use tomzx\HackBot\Core\User;
use tomzx\HackBot\Core\Responders\Command;

return [
	'type' => 'command',
	'identifier' => 'permission-deny',
	'command' => 'permission-deny',
	'parameters' => '(?<user>\S+) (?<permissions>.*)',
	'help' => 'user permission [permissions ...]',
	'answer' => function (Dispatcher $dispatcher, array $data = [])
	{
		// TODO: Only allow logged-in/server authenticated users to give users permissions
		$adapter = Arry::get($data, 'meta.irc.adapter');
		if ( ! $adapter) {
			return;
		}

		$from = Arry::get($data, 'meta.irc.nick');
		$user = Arry::get($data, 'user');
		$permissions = explode(' ', Arry::get($data, 'permissions'));

		$lockManager = $dispatcher->getLockManager();

		$fromLock = $lockManager->caller(new User($from));

		if ( ! $fromLock->can('permissions.write')) {
			return 'You are not allowed to edit permissions.';
		}

		$userLock = $lockManager->caller(new User($user));

		foreach ($permissions as $permission) {
			$userLock->deny($permission);
		}

		return 'The following permissions were removed from user '.$user.': '.implode(', ', $permissions);
	}
];


text:
package com.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

public class ConvertToStringLiteralAction implements IntentionAction {
  @NotNull
  @Override
  public String getText() {
    return QuickFixBundle.message("convert.to.string.text");
  }

  @NotNull
  @Override
  public String getFamilyName() {
    return QuickFixBundle.message("convert.to.string.family");
  }

  @Override
  public boolean isAvailable(@NotNull final Project project, final Editor editor, final PsiFile file) {
    final PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
    return PsiUtil.isJavaToken(element, JavaTokenType.CHARACTER_LITERAL);
  }

  @Override
  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
    final PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
    if (element != null && PsiUtil.isJavaToken(element, JavaTokenType.CHARACTER_LITERAL)) {
      final String text = StringUtil.unescapeStringCharacters(element.getText());
      final int length = text.length();
      if (length > 1 && text.charAt(0) == '\'' && text.charAt(length - 1) == '\'') {
        final String value = StringUtil.escapeStringCharacters(text.substring(1, length - 1));
        final PsiExpression expression = JavaPsiFacade.getElementFactory(project).createExpressionFromText('"' + value + '"', null);
        final PsiElement literal = expression.getFirstChild();
        if (literal != null && PsiUtil.isJavaToken(literal, JavaTokenType.STRING_LITERAL)) {
          element.replace(literal);
        }
      }
    }
  }

  @Override
  public boolean startInWriteAction() {
    return true;
  }
}


text:
'use strict';
/*global angular:false, d3:false, fc:false, window:false, screen:false, console:false */

angular.module('argus.services.charts.tools', [])
.service('ChartToolService', ['UtilService', function(UtilService) {

	this.getTimeAxis = function(timeSpan) {
		var hours = [
			'12AM', '1AM', '2AM', '3AM', '4AM', '5AM',
			'6AM', '7AM', '8AM', '9AM', '10AM', '11AM',
			'12PM', '1PM', '2PM', '3PM', '4PM', '5PM',
			'6PM', '7PM', '8PM', '9PM', '10PM', '11PM'
		];
		var axis = [];
		var firstHour = (new Date(timeSpan.begin)).getHours();
		for (var i = 0; i < timeSpan.span; i++) {
			axis.push(hours[(firstHour + i) % 24]);
		}
		axis.push('Average');
		return axis;
	};

	// layout dimension
	var marginTopSmall= 5,
		marginRightSmall= 5;
	var marginTop = 15,
		marginBottom = 35,
		marginLeft = 50,
		marginRight= 60;
	var mainChartRatio = 0.8, //ratio of height
		brushChartRatio = 0.15;

	var bufferRatio = 0.2; // the ratio of buffer above/below max/min on yAxis for better showing experience

	this.extraYAxisPadding = 35;
	this.defaultHeatmapIntervalInMinutes = 30;
	this.defaultHeatmapNumOfBucket = 5;
	this.defaultAggregateType = 'avg';
	this.syncChartJobs = {};
	this.defaultTileColor = 'steelblue';

	this.getOrCreateSyncChartJobs = function(dashboardId){
		if(!this.syncChartJobs[dashboardId]){
			this.syncChartJobs[dashboardId] = {};
		}
		return this.syncChartJobs[dashboardId];
	};

	this.destroySyncChartJobs = function(dashboardId){
		delete this.syncChartJobs[dashboardId];
	};

	this.addSyncChartJob = function(dashboarId, chartId, syncChartJob){
		if(syncChartJob[dashboarId]){
			syncChartJob[dashboarId][chartId] = syncChartJob;
		}
	};

	this.calculateDimensions = function (newContainerWidth, newContainerHeight, isSmallChart, isBrushOn, extraYAxisNum) {
		var currentMarginTop = isSmallChart? marginTopSmall: marginTop;
		var currentMarginRight = isSmallChart? marginRightSmall: marginRight;
		var newWidth = newContainerWidth - marginLeft - currentMarginRight;
		var newHeight, newHeight2;

		// 'smallChart' setting: add to marginBottom, so xAxis has more room for rotated text labels
		var tmpMarginBottom = (isSmallChart)? marginBottom + 30 : marginBottom;

		if (isBrushOn) {
			newHeight = parseInt((newContainerHeight - currentMarginTop - tmpMarginBottom) * mainChartRatio);
			newHeight2 = parseInt((newContainerHeight - currentMarginTop - tmpMarginBottom) * brushChartRatio);
		} else {
			newHeight = parseInt(newContainerHeight - currentMarginTop - tmpMarginBottom);
			newHeight2 = 0;
		}

		var newMargin = {
			top: currentMarginTop,
			right: currentMarginRight,
			bottom: newContainerHeight - currentMarginTop - newHeight,
			left: marginLeft
		};
		var newMargin2 = {
			top: newContainerHeight - newHeight2 - tmpMarginBottom,
			right: currentMarginRight,
			bottom: tmpMarginBottom,
			left: marginLeft
		};
		return {
			width: newWidth - extraYAxisNum * this.extraYAxisPadding,
			widthFull: newWidth,
			height: newHeight,
			height2: newHeight2,
			margin: newMargin,
			margin2: newMargin2
		};
	};

	// date and formatting https://github.com/d3/d3-time-format/blob/master/README.md#timeFormat
	var numericalDate = '%-m/%-d/%y %H:%M:%S';
	var smallChartDate = '%x';  // %x = %m/%d/%Y  11/5/2016

	this.generateDateFormatter = function (isGMT, customizedFormat, isSmallChart) {
		var tmpDate;
		if (customizedFormat === undefined) {
			tmpDate = isSmallChart ? smallChartDate : numericalDate;
		} else {
			tmpDate = customizedFormat;
		}
		return isGMT? d3.utcFormat(tmpDate): d3.timeFormat(tmpDate);
	};

	this.bisectDate = d3.bisector(function (d) {
		return d[0];
	}).left;

	this.bisectDateStackedData = d3.bisector(function (d) {
		return d.data.timestamp;
	}).left;

	// menu option
	var sampleCustomFormat = '0,.8';     // scientific notation
	var defaultYaxis = '.3s';
	var defaultTicksYaxis = '5';

	this.rawDataFormat = ',';
	this.defaultMenuOption = {
		dateFormat: numericalDate,
		colorPalette: 'schemeCategory20',
		downSampleMethod: '',
		isSyncChart: false,
		isBrushMainOn: false,
		isWheelOn: false,
		isBrushOn: true,
		isTooltipOn: true,
		tooltipConfig: {
			rawTooltip: true,
			customTooltipFormat: sampleCustomFormat,
			leadingNum: null,
			trailingNum: null,
			isTooltipSortOn: true
		},
		yAxisConfig: {
			formatYaxis: defaultYaxis,
			numTicksYaxis: defaultTicksYaxis
		},
		isSnapCrosslineOn: true,
		localTimezone: false,
		showEmptyRange: false
	};
	this.defaultMenuOptionSmallChart = {
		dateFormat: numericalDate,
		colorPalette: 'schemeCategory20',
		downSampleMethod: '',
		isSyncChart: false,
		isBrushMainOn: false,
		isWheelOn: true,
		isBrushOn: false,
		isTooltipOn: true,
		tooltipConfig: {
			rawTooltip: true,
			customTooltipFormat: sampleCustomFormat,
			leadingNum: null,
			trailingNum: null,
			isTooltipSortOn: true
		},
		yAxisConfig: {
			formatYaxis: defaultYaxis,
			numTicksYaxis: defaultTicksYaxis
		},
		isSnapCrosslineOn: true,
		localTimezone: false,
		showEmptyRange: false
	};

	// color
	this.setColorScheme = function (colorPalette) {
		var result;
		switch (colorPalette) {
			case 'schemeCategory10':
				result = d3.scaleOrdinal(d3.schemeCategory10);
				break;
			case 'schemeCategory20b':
				result = d3.scaleOrdinal(d3.schemeCategory20b);
				break;
			case 'schemeCategory20c':
				result = d3.scaleOrdinal(d3.schemeCategory20c);
				break;
			default:
				result = d3.scaleOrdinal(d3.schemeCategory20);
		}
		return result;
	};

	this.bindDefaultColorsWithSources = function (colorZ, sourceNames) {
		colorZ.domain(sourceNames);
	};

	// other constants
	this.yAxisPadding = 1;

	// other things
	this.defaultEmptyGraphMessage = 'No graph available';

	this.getXandY = function (timeInfo, isGMT, sizeInfo, yScaleType, yScaleConfigValue) {
		var xScale = isGMT? d3.scaleUtc(): d3.scaleTime();
		var y = this.getY(sizeInfo, yScaleType, yScaleConfigValue);
		return {
			x: xScale.domain([timeInfo.startTime, timeInfo.endTime]).range([0, sizeInfo.width]),
			y: y.y,
			yScalePlain: y.yScalePlain
		};
	};

	this.getColorScale = function(sizeInfo){
		return  d3.scaleLiner().range([0, sizeInfo.width]);
	};

	this.getY = function (sizeInfo, yScaleType, yScaleConfigValue){
		var yScale, yScalePlain;
		if (yScaleConfigValue === undefined || isNaN(yScaleConfigValue)) yScaleConfigValue = 10;
		switch (yScaleType) {
			case 'log':
				yScale = d3.scaleLog().base(yScaleConfigValue);
				yScalePlain = d3.scaleLog().base(yScaleConfigValue);
				break;
			case 'power':
				yScale = d3.scalePow().exponent(yScaleConfigValue);
				yScalePlain = d3.scalePow().exponent(yScaleConfigValue);
				break;
			// case 'linear':
			default:
				yScale = d3.scaleLinear();
				yScalePlain = d3.scaleLinear();
		}

		return {
			y: yScale.range([sizeInfo.height, 0]),
			yScalePlain: yScalePlain
		};
	};

	this.generateTimestampSelector = function (isDataStacked) {
		return isDataStacked ? function (d) {return d.data.timestamp;} : function (d) {return d[0];};
	};

	this.getXandYDomainsOfSeries = function (series, isChartDiscrete, isDataStacked, timestampSelector, extraYAxisSet) {
		var datapoints = [];
		var extraDatapoints = {};
		var allDatapoints = [];
		for(var iSet of extraYAxisSet){
			extraDatapoints[iSet] = [];
		}

		series.forEach(function (metric) {
			if (metric.extraYAxis) {
				extraDatapoints[metric.extraYAxis] = extraDatapoints[metric.extraYAxis].concat(metric.data);
			} else {
				datapoints = datapoints.concat(metric.data);
			}
			allDatapoints = allDatapoints.concat(metric.data);
		});

		var result = {
			xDomain: this.getXDomainOfSeries(allDatapoints, timestampSelector),
			yDomain: this.getYDomainOfSeries(datapoints, isDataStacked),
			extraYDomain: this.getExtraYDomainOfSeries(extraDatapoints, extraYAxisSet)
		};

		if (isChartDiscrete) result.discreteXDomain = this.getDiscreteXDomainOfSeries(allDatapoints, timestampSelector);

		return result;
	};

	this.getXDomainOfSeries = function (dataPoints, timestampSelector) {
		var extent;
		extent = d3.extent(dataPoints, function (d) {
			return timestampSelector(d);
		});
		return extent;
	};

	this.getDiscreteXDomainOfSeries = function (datapoints, timestampSelector) {
		var result = [];
		datapoints.map(function (d) {
			var newTimestamp = timestampSelector(d);
			if (!result.includes(newTimestamp)) result.push(newTimestamp);
		});
		return result.sort();
	};

	this.getYDomainOfSeries = function (dataPoints, isDataStacked) {
		var extent;
		if (isDataStacked) {
			if (dataPoints === undefined || dataPoints.length === 0) {
				extent = [0, 0];
			} else {
				var yMin = Number.MAX_VALUE, yMax = Number.MAX_VALUE * (-1);
				dataPoints.map(function (d) {
					if (d[0] < yMin) yMin = d[0];
					if (d[1] > yMax) yMax = d[1];
				});
				extent = [yMin, yMax];
			}
		} else {
			extent = d3.extent(dataPoints, function (d) { return d[1]; });
		}
		return extent;
	};

	this.getExtraYDomainOfSeries = function (extraDatapoints, extraYAxisSet){
		var extraYDomain = {};

		for(var iSet of extraYAxisSet){
			extraYDomain[iSet] = d3.extent(extraDatapoints[iSet], function (d) {
				return d[1];
			});
		}

		return extraYDomain;
	};

	this.updateXandYRange = function (sizeInfo, x, y, needToAdjustHeight) {
		if (needToAdjustHeight) {
			y.range([sizeInfo.height, 0]);
		}
		x.range([0, sizeInfo.width]);
	};

	this.updateExtraYRange = function (sizeInfo, extraY, extraYAxisSet){
		if (extraYAxisSet){
			for(var iSet of extraYAxisSet){
				extraY[iSet].range([sizeInfo.height, 0]);
			}
		}
	};

	this.getSubDiscreteXDomain = function (discreteXDomain, newExtent) {
		var startTime = typeof newExtent[0] === 'number' ? newExtent[0] : newExtent[0].getTime();
		var endTime = typeof newExtent[1] === 'number' ? newExtent[1] : newExtent[1].getTime();
		var startIndex = discreteXDomain.indexOf(startTime);
		var endIndex = discreteXDomain.indexOf(endTime);
		if (startIndex === -1) startIndex = d3.bisectLeft(discreteXDomain, startTime) - 1;
		if (endIndex === -1) endIndex = d3.bisectRight(discreteXDomain, endTime);
		return discreteXDomain.slice(startIndex, endIndex + 1);
	};

	this.createSourceListForLegend = function (names, graphClassNames, colors, colorZ) {
		var tmpSources = [];
		for (var i = 0; i < names.length; i++) {
			var tempColor = colors[i] === null ? colorZ(names[i]) : colors[i];
			tmpSources.push({
				name: names[i],
				displaying: true,
				color: tempColor,
				graphClassName: graphClassNames[i]
			});
		}
		return tmpSources;
	};

	var everyNthPoint = function () {
		var bucketSize = 1;
		var everyNthPoint = function(data){
			var temp = [];
			for(var i = 0; i < data.length; i+=bucketSize){
				temp.push(data[i]);
			}
			return temp;
		};
		everyNthPoint.bucketSize = function(size){
			bucketSize = size;
		};
		return everyNthPoint;
	};

	// var downsampleThreshold = 1/2; // datapoints per pixel
	this.downSample = function (series, containerWidth, downSampleMethod, downSampleThreshold) {
		if (downSampleThreshold === undefined) downSampleThreshold = 0.5;
		if (!series) return series;
		if (downSampleMethod === '' || downSampleMethod === undefined) return series;
		// var temp = angular.copy(series);
		var temp = series.map(function(metric) {
			return UtilService.objectWithoutProperties(metric, ['data']);
		});

		// Create the sampler
		var sampler;
		switch (downSampleMethod){
			case 'largest-triangle-one-bucket':
				sampler = fc.largestTriangleOneBucket();
				// Configure the x / y value accessors
				sampler.x(function(d) {return d[0];})
						.y(function(d){return d[1];});
				break;
			case 'largest-triangle-three-bucket':
				sampler = fc.largestTriangleThreeBucket();
				// Configure the x / y value accessors
				sampler.x(function(d) {return d[0];})
						.y(function(d){return d[1];});
				break;
			case 'mode-median':
				sampler = fc.modeMedian();
				sampler.value(function(d){return d[1];});
				break;
			case 'every-nth-point':
				sampler = everyNthPoint();
				break;
		}

		// Run the sampler
		if (sampler) {
			series.forEach(function(metric, index){
				//determine whether to downsample or not
				//downsample if there are too many datapoints per pixel
				if (metric.data.length / containerWidth > downSampleThreshold) {
					//determine bucket size
					var bucketSize = Math.ceil(metric.data.length / (downSampleThreshold * containerWidth));
					// Configure the size of the buckets used to downsample the data.
					sampler.bucketSize(bucketSize);
					temp[index].data  = sampler(metric.data);
				} else {
					// no need to downsample; just copy over the data
					temp[index].data  = angular.copy(metric.data);
				}
			});
		}

		return temp;
	};

	this.downSampleASingleMetricsDataEveryTenPoints = function (metric, containerWidth) {
		if (metric.data.length / containerWidth > 0.1) {
			// var result = angular.copy(metric);
			var result = UtilService.objectWithoutProperties(metric, ['data']);
			var sampler = everyNthPoint();
			var bucketSize = Math.ceil(metric.data.length / (0.1 * containerWidth));
			sampler.bucketSize(bucketSize);
			result.data = sampler(metric.data);
			return result;
		} else {
			return metric;
		}
	};

	this.setZoomExtent = function (series, zoom, k) {
		//extent, k is the least number of points in one line you want to see on the main chart view
		var numOfPoints = series[0].data.length;
		for (var i = 1; i < series.length; i++) {
			if (numOfPoints < series[i].data.length) {
				numOfPoints = series[i].data.length;
			}
		}
		if (!k || k > numOfPoints) k = 3;
		zoom.scaleExtent([1, numOfPoints / k]);
		return parseInt(numOfPoints / k);
	};

	this.isBrushInNonEmptyRange = function (xDomain, dateExtent) {
		return xDomain[0] <= dateExtent[1] && xDomain[xDomain.length - 1] >= dateExtent[0];
	};

	this.isNotInTheDomain = function (value, domainArray) {
		return value < domainArray[0] || value > domainArray[domainArray.length - 1];
	};

	this.isMetricNotInTheDomain = function (metric, xDomain, timestampSelector) {
		var len = metric.data.length;
		if (len < 1) return false;
		var startPoint = timestampSelector(metric.data[0]);
		var endPoint = timestampSelector(metric.data[len - 1]);
		return startPoint > xDomain[xDomain.length - 1] || endPoint < xDomain[0];
	};
	var isMetricNotInTheDomain = this.isMetricNotInTheDomain;

	this.updateContainerSize = function (container, defaultContainerHeight, defaultContainerWidth, isSmallChart, isBrushOn, changeToFullscreen, extraYAxisNum) {
		var containerWidth, containerHeight;
		if (changeToFullscreen && (window.innerHeight === screen.height || container.offsetHeight === window.innerHeight)) {
			// set the graph size to be the same as the screen
			containerWidth = screen.width;
			containerHeight = screen.height * 0.95;
		} else {
			// default containerHeight will be used
			containerHeight = defaultContainerHeight;
			// no width defined via chart option: window width will be used
			containerWidth = defaultContainerWidth < 0 ? container.offsetWidth : defaultContainerWidth;
		}
		var newSize = this.calculateDimensions(containerWidth, containerHeight, isSmallChart, isBrushOn, extraYAxisNum);
		return {
			newSize: newSize,
			containerWidth: containerWidth,
			containerHeight: containerHeight
		};
	};

	this.calculateGradientOpacity = function (num, tot) {
		return 0.9 - 0.7 * (num / tot);
	};

	var findValueAtAGivenTimestamp = function (metric, timestamp, startingIndex) {
		for (var i = startingIndex; i < metric.data.length; i++) {
			if (metric.data[i][0] === timestamp) {
				return {
					index: i,
					value: metric.data[i][1]
				};
			}
		}
	};

	this.convertSeriesToTimeBasedFormat = function (series, metricsToIgnore) {
		var result = [];
		var allTimestamps = [];
		var valuesAtPreviousTimestampWithIndex = {};

		var needToIgnoreSomeMetrics = metricsToIgnore !== undefined && metricsToIgnore.length !== 0;
		series.map(function(metric) {
			if (needToIgnoreSomeMetrics && metricsToIgnore.includes(metric.name)) return;
			valuesAtPreviousTimestampWithIndex[metric.name] = {value: 0, index: 0};
			metric.data.map(function(d) {
				var timestamp = d[0];
				if (!allTimestamps.includes(timestamp)) allTimestamps.push(timestamp);
			});
		});

		// sort the timestamps and add values from each source
		allTimestamps.sort(function(a, b) { return a - b; });
		allTimestamps.map(function(timestamp) {
			var valuesAtThisTimestamp = {timestamp: timestamp};
			series.map(function(metric) {
				if (needToIgnoreSomeMetrics && metricsToIgnore.includes(metric.name)) return;
				var tempValueWithIndex = findValueAtAGivenTimestamp(metric, timestamp, valuesAtPreviousTimestampWithIndex[metric.name].index);
				// use previous value when there is no data for this timestamp
				if (tempValueWithIndex === undefined) {
					if (valuesAtPreviousTimestampWithIndex[metric.name] !== undefined) {
						tempValueWithIndex = valuesAtPreviousTimestampWithIndex[metric.name];
					} else {
						tempValueWithIndex = { value: 0, index: 0 };
						valuesAtPreviousTimestampWithIndex[metric.name] = tempValueWithIndex;
					}
				} else {
					valuesAtPreviousTimestampWithIndex[metric.name] = tempValueWithIndex;
				}
				valuesAtThisTimestamp[metric.name] = tempValueWithIndex.value;
			});
			result.push(valuesAtThisTimestamp);
		});
		return result;
	};

	this.getAggregatedSeriesAndXYZDomain = function(series, names, aggr, intervalInMinutes){
		var timeBasedSeries = this.convertSeriesToTimeBasedFormatKeepUndefined(series);
		return this.getAggregatedTimeBasedSeriesAndXYZDomain(timeBasedSeries, names, aggr, intervalInMinutes);
	};

	this.convertSeriesToTimeBasedFormatKeepUndefined = function (series) {
		var result = [];
		var allTimestamps = [];
		var valuesAtPreviousTimestampWithIndex = {};

		series.map(function(metric) {
			valuesAtPreviousTimestampWithIndex[metric.name] = {value: 0, index: 0};
			metric.data.map(function(d) {
				var timestamp = d[0];
				if (!allTimestamps.includes(timestamp)) allTimestamps.push(timestamp);
			});
		});

		// sort the timestamps and add values from each source
		allTimestamps.sort(function(a, b) { return a - b; });
		allTimestamps.map(function(timestamp) {
			var valuesAtThisTimestamp = {timestamp: timestamp};

			series.map(function(metric) {
				var tempValueWithIndex = findValueAtAGivenTimestamp(metric, timestamp, valuesAtPreviousTimestampWithIndex[metric.name].index);
				if(tempValueWithIndex !== undefined){
					valuesAtPreviousTimestampWithIndex[metric.name] = tempValueWithIndex;
					valuesAtThisTimestamp[metric.name] = tempValueWithIndex.value;
				}
			});
			result.push(valuesAtThisTimestamp);
		});
		return result;
	};

	this.getAggregatedTimeBasedSeriesAndXYZDomain = function(timeBasedSeries, names, aggr, intervalInMinutes) {
		intervalInMinutes = intervalInMinutes || this.defaultHeatmapIntervalInMinutes;
		var startOfInterval = timeBasedSeries[0].timestamp;
		var endOfInterval = startOfInterval + intervalInMinutes * 60000;
		var aggregatedSeries = [];
		var tempSum = {};
		var tempCount = {};
		var yDomain = [Number.MAX_VALUE, Number.MIN_VALUE];

		function aggregate() {
			if (aggr === 'sum') {
				var sum = {timestamp: startOfInterval};
				names.forEach(function (name) {
					if (tempSum[name] !== undefined) {
						var val = tempSum[name];
						if (val < yDomain[0]) {
							yDomain[0] = val;
						}
						if (val > yDomain[1]) {
							yDomain[1] = val;
						}
						sum[name] = val;
					}
				});
				aggregatedSeries.push(sum);
			} else if (aggr === 'avg') {
				var avg = {timestamp: startOfInterval};
				names.forEach(function (name) {
					if (tempSum[name] !== undefined) {
						var val = tempSum[name] / tempCount[name];
						if (val < yDomain[0]) {
							yDomain[0] = val;
						}
						if (val > yDomain[1]) {
							yDomain[1] = val;
						}
						avg[name] = val;
					}
				});
				aggregatedSeries.push(avg);
			}
		}

		timeBasedSeries.forEach(function (d) {
			if (d.timestamp < endOfInterval) {
				//keep adding
				names.forEach(function (name) {
					var val = d[name];
					if (val !== undefined) {
						if (tempSum[name]) {
							tempSum[name] += val;
							tempCount[name] += 1;
						} else {
							tempSum[name] = val;
							tempCount[name] = 1;
						}
					}
				});
			} else {
				//sum/avg this interval
				aggregate();
				startOfInterval = endOfInterval;
				endOfInterval = startOfInterval + intervalInMinutes * 60000;

				//start adding
				names.forEach(function (name) {
					var val = d[name];
					if (val !== undefined) {
						tempSum[name] = val;
						tempCount[name] = 1;
					}
				});
			}
		});

		//last interval
		if(timeBasedSeries[timeBasedSeries.length - 1].timestamp < endOfInterval){
			//sum/avg this interval
			aggregate();
		}
		return {
			aggregatedSeries: aggregatedSeries,
			xDomain: [timeBasedSeries[0].timestamp, timeBasedSeries[timeBasedSeries.length-1].timestamp],
			yDomain: yDomain,
			zDomain: [0, names.length]
		};
	};

	this.getHeatmapDataAndBucketInfo = function(aggregatedSeriesAndYDomain, bucketMin, step, numOfBucket){
		var heatmapData = [];
		var aggregatedSeries = aggregatedSeriesAndYDomain.aggregatedSeries;
		var yDomain = aggregatedSeriesAndYDomain.yDomain;
		numOfBucket = numOfBucket || this.defaultHeatmapNumOfBucket;
		bucketMin = this.getTheNumberValueFromTwo(bucketMin, yDomain[0]);
		step = step || (yDomain[1] - bucketMin) / numOfBucket;
		var bucketMax = bucketMin + step * numOfBucket;

		//transfer to time, bucket, frequency
		aggregatedSeries.forEach(function(d){
			var temp = [];
			for(var i = 0; i < numOfBucket; i++){
				temp[i] = {
					bucket: bucketMin + i * step,
					count: 0,
					names: []
				};
			}
			for(var k in d){
				if(d.hasOwnProperty(k)){
					if (k !== 'timestamp'){
						for(i = 0; i < numOfBucket; i++){
							if(d[k] < bucketMin + step * (i + 1)){
								temp[i].count += 1;
								temp[i].names.push(k);
								break;
							}
						}
						if(d[k] === bucketMax){
							temp[numOfBucket - 1].count += 1;
							temp[numOfBucket - 1].names.push(k);
						}
					}
				}
			}
			temp.forEach(function(e){
				heatmapData.push({
					timestamp: d.timestamp,
					bucket: e.bucket,
					frequency: e.count,
					names: e.names
				});
			});

		});

		return{
			newYDomain: [bucketMin, bucketMin + step * numOfBucket],
			heatmapData: heatmapData,
			numOfBucket: numOfBucket,
			bucketMin: bucketMin,
			step: step
		};
	};

	this.addStackedDataToSeries = function (series, stack, metricsToIgnore) {
		var stackedData = stack(this.convertSeriesToTimeBasedFormat(series, metricsToIgnore));
		var newSeries = series.map(function (metric, index) {
			var newMetric = UtilService.objectWithoutProperties(metric, ['data']);
			newMetric.data = stackedData[index];
			return newMetric;
		});
		return newSeries;
	};

	this.adjustSeriesBeingDisplayed = function (series, x, timestampSelector, dateBisector) {
		var xDomain = x.domain();
		var newDisplayingSeries = series.map(function(metric) {
			return UtilService.objectWithoutProperties(metric, ['data']);
		});
		series.forEach(function (metric, index) {
			if (isMetricNotInTheDomain(metric, xDomain, timestampSelector)) {
				newDisplayingSeries[index].data = [];
				return;
			}
			var start, end;
			start = dateBisector(metric.data, xDomain[0]);
			if (start > 0) start -= 1; //to avoid cut off issue on the edge
			end = dateBisector(metric.data, xDomain[1], start) + 1; //to avoid cut off issue on the edge
			newDisplayingSeries[index].data = metric.data.slice(start, end + 1);
		});
		return newDisplayingSeries;
	};

	this.findMatchingMetricInSources = function (metric, sources) {
		return sources.filter(function(source) {
			return source.name === metric.name;
		})[0];
	};

	this.processYDomain = function (currentExtent, yScalePlain, yScaleType, agYMin, agYMax, isDataStacked, isChartDiscrete) {
		var yMin, yMax, buffer, finalYMin, finalYMax;
		yMin = UtilService.validNumberChecker(yScalePlain(currentExtent[0]));
		yMax = UtilService.validNumberChecker(yScalePlain(currentExtent[1]));
		buffer = (yMax - yMin) * bufferRatio;
		if (buffer === 0) buffer = this.yAxisPadding;

		finalYMin = (agYMin === undefined) ? UtilService.validNumberChecker(yScalePlain.invert(yMin - buffer)): agYMin;
		finalYMax = (agYMax === undefined) ? UtilService.validNumberChecker(yScalePlain.invert(yMax + 1.2 * buffer)): agYMax;
		// TODO: need to test with negative values for area and bar charts
		if (isDataStacked && finalYMin < 0 && yMin !== yMax) finalYMin = 0;
		// if (isChartDiscrete && finalYMin < 0 && yMin < yMax) finalYMin = 0;
		if (isChartDiscrete && !isDataStacked && finalYMin > 0 && yMin < yMax) {
			finalYMin = 0;
			finalYMax *= 1.2;
		}
		// TODO: still need to handle log(0) better
		if (yScaleType === 'log') {
			if (finalYMin === 0) finalYMin = 1;
			if (finalYMax === 0) finalYMax = 1;
		}

		return [finalYMin, finalYMax];
	};

	this.getTileData = function(heatmapData, graph, mouseData, bucketInfo){
		var xIndex = Math.floor((mouseData.mouseX - graph.x.domain()[0])/bucketInfo.xStep);
		var yIndex = Math.floor((mouseData.mouseY - graph.y.domain()[0])/bucketInfo.yStep);
		var index = bucketInfo.numOfYStep * xIndex + yIndex;
		var tileData = heatmapData[index];
		return {
			data: tileData,
			xIndex: xIndex,
			yIndex: yIndex
		};
	};

	this.getGraphClassNamesMap = function(series){
		var map = {};
		series.forEach(function(metric){
			map[metric.name] = metric.graphClassName;
		});
		return map;
	};

	this.Number = function(a){
		if(typeof(a) === "string" && a.trim() === "") return NaN;
		return Number(a);
	};

	this.isNaN = function (a) {
		if(typeof(a) === "string" && a.trim() === "") return true;
		return isNaN(a);
	};

	this.getTheNumberValueFromTwo = function(a, b){
		return (this.isNaN(a) ? Number(b) : Number(a));
	};

	this.getTheNumberValueFromThree = function(a, b, c){
		var temp = (this.isNaN(a) ? Number(b) : Number(a));
		return this.isNaN(temp) ? Number(c) : temp;
	};

	this.equalTimeDomain = function(domain1, domain2) {
		return (new Date(domain1[0]).getTime() === new Date(domain2[0]).getTime()) &&
				(new Date(domain1[1]).getTime() === new Date(domain2[1]).getTime());
	};
}]);


text:
using System.Threading.Tasks;
using HockeyApp.Contracts.Dto.Announcements;
using HockeyApp.Contracts.Requests.Announcements;

namespace HockeyApp.Services.Announcements.Contracts
{
    public interface IСampAnnouncementResponseNoteService
    {
        Task<long> CreateСampAnnouncementResponseNote(СampAnnouncementResponseNoteCreateRequest request);
        Task<СampAnnouncementResponseNoteDto> UpdateСampAnnouncementResponseNote(long id, СampAnnouncementResponseNoteUpdateRequest request);
        Task DeleteСampAnnouncementResponseNote(long id);
    }
}


text:
package com.fishercoder.solutions;

public class _1518 {
    public static class Solution1 {
        public int numWaterBottles(int numBottles, int numExchange) {
            int drunk = numBottles;
            int emptyBottles = numBottles;
            while (emptyBottles >= numExchange) {
                int exchangedBottles = emptyBottles / numExchange;
                drunk += exchangedBottles;
                int unUsedEmptyBottles = emptyBottles % numExchange;
                emptyBottles = exchangedBottles + unUsedEmptyBottles;
            }
            return drunk;
        }
    }
}


text:
require 'spec_helper'

describe XClarityClient do
  before do
    conf = XClarityClient::Configuration.new(
      :username   => ENV['LXCA_USERNAME'],
      :password   => ENV['LXCA_PASSWORD'],
      :host       => ENV['LXCA_HOST'],
      :port       => ENV['LXCA_PORT'],
      :auth_type  => ENV['LXCA_AUTH_TYPE'],
      :verify_ssl => ENV['LXCA_VERIFY_SSL']
    )

    @client = XClarityClient::Client.new(conf)
    @req_stub = stub_request(:get, "#{ENV['LXCA_HOST']}/remoteaccess/remoteControl?uuid=#{uuid}")
  end

  describe '#remote_control' do
    subject { @client.remote_control(uuid) }

    let(:uuid) { '1234' }

    context 'when the API responds with Content-Type application/json' do
      before do
        @req_stub.to_return(:body => {:url => 'my_url'}.to_json, :headers => { 'Content-Type' => 'other;application/json;other' })
      end

      it { is_expected.to have_attributes(:type => :url, :resource => 'my_url') }
    end

    context 'when the API responds with Content-Type application/com.lenovo.lxca-v2.0.0+json; charset=ISO-8859-1' do
      before do
        @req_stub.to_return(:body => {:url => 'my_url'}.to_json, :headers => { 'Content-Type' => 'application/com.lenovo.lxca-v2.0.0+json; charset=ISO-8859-1' })
      end

      it { is_expected.to have_attributes(:type => :url, :resource => 'my_url') }
    end

    context 'when the API responds with Content-Type application/x-java-jnlp-file' do
      before do
        @req_stub.to_return(:body => '<my_jnlp></my_jnlp>', :headers => { 'Content-Type' => 'other;application/x-java-jnlp-file;other' })
      end

      it { is_expected.to have_attributes(:type => :java_jnlp_file, :resource => '<my_jnlp></my_jnlp>') }
    end

    context 'when the API responds with an unknown Content-Type' do
      before do
        @req_stub.to_return(:headers => { 'Content-Type' => 'other;application/xml;other' })
      end

      it 'is expected to raise a Unkown header error' do
        expect { @client.remote_control(uuid) }.to raise_error(RuntimeError, 'Unexpected Content-Type header')
      end
    end

    context 'when the server responds with an error status' do
      before do
        @req_stub.to_return(:status => [500, "Internal Server Error"])
      end

      it 'is expected to raise a Request failed error' do
        expect { @client.remote_control(uuid) }.to raise_error(RuntimeError, 'Request failed')
      end
    end

    context 'when an empty uuid is provided' do
      let(:uuid) { '' }

      it 'is expected to raise an error' do
        expect { @client.remote_control(uuid) }.to raise_error(RuntimeError, 'UUID must not be blank')
      end
    end

    context 'when a nil uuid is provided' do
      let(:uuid) { nil }

      it 'is expected to raise an error' do
        expect { @client.remote_control(uuid) }.to raise_error(RuntimeError, 'UUID must not be blank')
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/objects/food-and-beverages/food/ribs" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/food-and-beverages/food/ribs</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Ribs</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/food-and-beverages/food/ribs</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/food-and-beverages/food/ribs</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy Fame
 *
 * DEVICE: nevis3g
 * MODEL: GT-S6812i
 */
final class nevis3g {
    public static final String DATA = "Samsung|Galaxy Fame|";
}


text:
// This is a translation to C# from the original C++ code of the Geometric Tool Library
// Original license
// David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06

namespace netDxf.GTE
{
    internal abstract class ParametricSurface
    {
        protected double mUMin, mUMax, mVMin, mVMax;
        protected bool mRectangular;
        protected bool mConstructed;

        // Abstract base class for a parameterized surface X(u,v).  The
        // parametric domain is either rectangular or triangular.  Valid
        // (u,v) values for a rectangular domain satisfy
        //   umin <= u <= umax,  vmin <= v <= vmax
        // and valid (u,v) values for a triangular domain satisfy
        //   umin <= u <= umax,  vmin <= v <= vmax,
        //   (vmax-vmin)*(u-umin)+(umax-umin)*(v-vmax) <= 0
        protected ParametricSurface(double umin, double umax, double vmin, double vmax, bool rectangular)
        {
            this.mUMin = umin;
            this.mUMax = umax;
            this.mVMin = vmin;
            this.mVMax = vmax;
            this.mRectangular = rectangular;
            this.mConstructed = false;
        }

        // Member access.

        // To validate construction, create an object as shown:
        //     DerivedClassSurface<Real> surface(parameters);
        //     if (!surface) { <constructor failed, handle accordingly>; }
        public bool IsConstructed
        {
            get { return this.mConstructed; }
        }

        public double UMin
        {
            get { return this.mUMin; }
        }

        public double UMax
        {
            get { return this.mUMax; }
        }

        public double VMin
        {
            get { return this.mVMin; }
        }

        public double VMax
        {
            get { return this.mVMax; }
        }

        public bool IsRectangular
        {
            get { return this.mRectangular; }
        }

        // Evaluation of the surface.  The function supports derivative
        // calculation through order 2; that is, order <= 2 is required.  If
        // you want only the position, pass in order of 0.  If you want the
        // position and first-order derivatives, pass in order of 1, and so
        // on.  The output array 'jet' must have enough storage to support the
        // maximum order.  The values are ordered as: position X; first-order
        // derivatives dX/du, dX/dv; second-order derivatives d2X/du2,
        // d2X/dudv, d2X/dv2.
        public const int SUP_ORDER = 6;

        public abstract void Evaluate(double u, double v, int order, out Vector3[] jet);

        // Differential geometric quantities.
        public Vector3 GetPosition(double u, double v)
        {
            this.Evaluate(u, v, 0, out Vector3[] jet);
            return jet[0];
        }

        public Vector3 GetUTangent(double u, double v)
        {
            this.Evaluate(u, v, 1, out Vector3[] jet);
            return Vector3.Normalize(jet[1]);
        }

        public Vector3 GetVTangent(double u, double v)
        {
            this.Evaluate(u, v, 1, out Vector3[] jet);
            return Vector3.Normalize(jet[2]);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                  http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Application\Sonata\UserBundle\Entity\User" table="fos_user_user">

        <id name="id" column="id" type="integer">
            <generator strategy="AUTO" />
        </id>
        <many-to-one field="membership" target-entity="Yorku\JuturnaBundle\Entity\MemberShip" inversed-by="users"/>
        <one-to-many field="useruploadfiles" target-entity="Map2u\CoreBundle\Entity\UserUploadfile" mapped-by="user">
            <cascade>
                <cascade-persist/>
                <cascade-remove/>
            </cascade>
        </one-to-many>
         <one-to-many field="categories" target-entity="Map2u\CoreBundle\Entity\Category" mapped-by="user">
            <cascade>
                <cascade-persist/>
                <cascade-remove/>
            </cascade>
        </one-to-many>
          <one-to-many field="maplayers" target-entity="Map2u\CoreBundle\Entity\MapLayer" mapped-by="user">
            <cascade>
                <cascade-persist/>
                <cascade-remove/>
            </cascade>
        </one-to-many>
    </entity>
</doctrine-mapping>


text:
package org.fcrepo.client.console.management;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.xml.rpc.ServiceException;

import org.fcrepo.client.Administrator;
import org.fcrepo.client.console.Console;
import org.fcrepo.client.console.ConsoleCommand;
import org.fcrepo.client.console.ConsoleSendButtonListener;
import org.fcrepo.client.console.ServiceConsoleCommandFactory;
import org.fcrepo.client.mtom.APIMStubFactory;

/**
 * @author Chris Wilper
 * @version $Id$
 */
public class ManagementConsole
        extends JInternalFrame
        implements Console {

    private static final long serialVersionUID = 1L;

    private final Administrator m_mainFrame;

    private final JTextArea m_outputArea;

    private final JTextField m_hostTextField;

    private final JTextField m_portTextField;

    private final JTextField m_contextTextField;

    private boolean m_isBusy;

    public ManagementConsole(Administrator mainFrame) {
        super("Management Console", true, //resizable
              true, //closable
              true, //maximizable
              true);//iconifiable
        m_mainFrame = mainFrame;
        m_outputArea = new JTextArea();
        m_outputArea.setFont(new Font("Serif", Font.PLAIN, 16));
        m_outputArea.setEditable(false);

        JScrollPane outputScrollPane = new JScrollPane(m_outputArea);
        outputScrollPane
                .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        outputScrollPane.setPreferredSize(new Dimension(250, 250));
        outputScrollPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 0));

        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new BorderLayout());
        JPanel hostPortPanel = new JPanel();

        hostPortPanel.setLayout(new BorderLayout());
        JPanel hostPanel = new JPanel();
        hostPanel.setLayout(new BorderLayout());
        hostPanel.add(new JLabel("Host : "), BorderLayout.WEST);
        m_hostTextField = new JTextField(Administrator.getHost(), 13);
        hostPanel.add(m_hostTextField, BorderLayout.EAST);

        JPanel portPanel = new JPanel();
        portPanel.setLayout(new BorderLayout());
        portPanel.add(new JLabel("  Port : "), BorderLayout.WEST);
        m_portTextField =
                new JTextField(new Integer(Administrator.getPort()).toString(),
                               4);
        portPanel.add(m_portTextField, BorderLayout.EAST);

        JPanel contextPanel = new JPanel();
        contextPanel.setLayout(new BorderLayout());
        contextPanel.add(new JLabel("  Context : "), BorderLayout.WEST);
        m_contextTextField =
                new JTextField(Administrator.getAppServContext(), 10);
        contextPanel.add(m_contextTextField, BorderLayout.EAST);

        hostPortPanel.add(hostPanel, BorderLayout.WEST);
        hostPortPanel.add(contextPanel, BorderLayout.CENTER);
        hostPortPanel.add(portPanel, BorderLayout.EAST);

        JPanel commandPanel = new JPanel();
        commandPanel.setLayout(new BorderLayout());
        commandPanel.add(new JLabel("  Command : "), BorderLayout.WEST);
        ConsoleCommand[] commands = null;
        try {
            commands =
                    ServiceConsoleCommandFactory
                            .getConsoleCommands(Class.forName("org.fcrepo.server.management.FedoraAPIM"),
                                                null);
        } catch (ClassNotFoundException cnfe) {
            System.out
                    .println("Could not find server management interface, FedoraAPIM.");
            System.exit(0);
        }

        JComboBox commandComboBox = new JComboBox(commands);
        commandComboBox.setSelectedIndex(0);
        commandPanel.add(commandComboBox);
        JButton sendButton = new JButton(" Send.. ");
        sendButton
                .addActionListener(new ConsoleSendButtonListener(commandComboBox
                                                                         .getModel(),
                                                                 m_mainFrame,
                                                                 this));

        commandPanel.add(sendButton, BorderLayout.EAST);

        controlPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        controlPanel.add(hostPortPanel, BorderLayout.WEST);
        controlPanel.add(commandPanel);

        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(controlPanel, BorderLayout.NORTH);
        getContentPane().add(outputScrollPane);

        ImageIcon hostIcon =
                new ImageIcon(ClassLoader.getSystemResource("images/client/standard/development/Host16.gif"));
        setFrameIcon(hostIcon);

        pack();
        int w = getSize().width;
        int h = getSize().height;
        if (w > Administrator.getDesktop().getWidth() - 10) {
            w = Administrator.getDesktop().getWidth() - 10;
        }
        if (h > Administrator.getDesktop().getHeight() - 10) {
            h = Administrator.getDesktop().getHeight() - 10;
        }
        setSize(w, h);
        m_isBusy = false;
    }

    @Override
    public void setBusy(boolean b) {
        m_isBusy = b;
        if (b) {
            getContentPane().setCursor(new Cursor(Cursor.WAIT_CURSOR));
        } else {
            getContentPane().setCursor(null);
        }
    }

    @Override
    public boolean isBusy() {
        return m_isBusy;
    }

    @Override
    public Object getInvocationTarget(ConsoleCommand cmd)
            throws InvocationTargetException {
        try {
            return APIMStubFactory.getStub(Administrator.getProtocol(),
                                           m_hostTextField.getText(),
                                           Integer.parseInt(m_portTextField
                                                   .getText()),
                                           Administrator.getUser(),
                                           Administrator.getPass());
        } catch (NumberFormatException nfe) {
            throw new InvocationTargetException(nfe, "Badly formed port");
        } catch (MalformedURLException murle) {
            throw new InvocationTargetException(murle, "Badly formed URL");
        } catch (ServiceException se) {
            throw new InvocationTargetException(se);
        }
    }

    @Override
    public void print(String output) {
        m_outputArea.append(output);
    }

    @Override
    public void clear() {
        m_outputArea.setText("");
    }

}


text:
name: Bug report
about: Create a report to help us improve
---

**Describe the bug**
_A clear and concise description of what the bug is_

**To Reproduce**
_Steps to reproduce the behavior_

Or better yet, provide a link to a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).

**Expected behavior**
_A clear and concise description of what you expected to happen_

**Screenshots**
_If applicable, add screenshots to help explain your problem_

**Additional context**
_Add any other context about the problem here_


text:
set -e

cwd=$(pwd)
cd $(dirname "$0")/..

source .travis/sanitize.sh
sanitize deploy

. quark-travis/bin/activate

if [[ -f ~/.nvm/nvm.sh ]]; then
    . ~/.nvm/nvm.sh
fi

set -x

npm install travis-after-all
if $(npm bin)/travis-after-all ; then
    SUCCESS="$?"
    echo "All tests in matrix passed, checking deployment conditions"
else
    SUCCESS="$?"
    case "$SUCCESS" in
        1)
            echo "Some tests in matrix failed, checking deployment conditions"
            ;;
        2)
            echo "I am not the master, done"
            exit 0
            ;;
        *)
            echo "Trouble with travis-after-all ($SUCCESS)"
            exit $SUCCESS
            ;;
    esac
fi

if [[ "$TRAVIS_REPO_SLUG" != "datawire/quark" ]]; then
    echo "Only CI for forks, skipping CD"
    exit $SUCCESS
fi

if [[ "$TRAVIS_PULL_REQUEST" != "false" ]]; then
    echo "Only CI for pull requests, skipping CD"
    exit $SUCCESS
fi

DEPLOY=false
STAGE=undefined

case "$SUCCESS-$TRAVIS_BRANCH" in
    0-master)
        DEPLOY="master"
        STAGE="initial"
        ;;
    1-master)
        DEPLOY="master"
        STAGE="failed"
        ;;
    0-develop | 0-quarkdev-ci)
        DEPLOY="develop"
        STAGE="initial"
        ;;
    1-develop | 1-quarkdev-ci)
        DEPLOY="develop"
        STAGE="failed"
        ;;
    *)
        echo "Only CI for branch $TRAVIS_BRANCH, skipping CD"
        exit $SUCCESS
        ;;
esac

if [[ "$CI" = "true" ]]; then
    echo "Setting up write access for github and pypi"
    git remote set-branches --add origin master && git fetch --unshallow
    git config --global credential.helper store
    git config --global user.email "automaton@datawire.io"
    git config --global user.name "Continuous Delivery"
    git config --global push.default simple
    ( set +x; echo "https://$GITHUB_ACCESS_TOKEN:x-oauth-basic@github.com" > ~/.git-credentials )
    ( set +x; cat <<EOF > ~/.pypirc
[distutils]
index-servers=pypi

[pypi]
repository = https://pypi.python.org/pypi
username = $ENCRYPTED_PYPI_USERNAME
password = $ENCRYPTED_PYPI_PASSWORD
EOF
      )
fi

case "$STAGE-$DEPLOY" in
    initial-master)
        echo "TODO MASTER DEPLOY"
        exit 1
        ;;

    initial-develop)
        pip install twine sphinx-better-theme
        NEXT_VERSION=$(scripts/compute-next-version)
        TAG="dev-$NEXT_VERSION"
        COMMIT=$(git rev-parse HEAD)
        ./release version --dev "$NEXT_VERSION"
        ./release --cicd push-docs
        ./release --cicd push-pkgs
        git tag -a -m "CI tests pass for $TAG" "$TAG" "$COMMIT"
        git push origin "$TAG"
        exit $SUCCESS
        ;;

    failed-master)
        echo "TODO: tag failed release build?"
        exit $SUCCESS
        ;;

    failed-develop)
        echo "TODO: tag failed dev build?"
        exit $SUCCESS
        ;;

    *)
        echo "Unhandled deploy mode $STAGE-$DEPLOY"
        exit 1
        ;;
esac


text:
/*
 * THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT CHANGE IT!
 *
 * This file was generated using the Allogen bridge tool. If
 * you wish to make changes to it, you must edit the original
 * interface declaration file and regenerate the bridge code.
 */

using System;
using System.Runtime.InteropServices;

using Allogen.Example.Inheritance;

namespace Allogen.Example.Inheritance {
    /**
     * Calls the C++ SubClass2() native method
     */
    public class SubClass2 : Allogen.Example.Inheritance.BaseClass {
        public SubClass2(IntPtr pointer) : base(pointer) {
            Pointer = pointer;
        }

        /**
         * Calls the C++ () native method
         */
        public SubClass2() : base(IntPtr.Zero) {
            Pointer = AllogenPInvoke.Constructor();
        }

        /**
         * This method deletes the wrapped C++ object. This method should
         * not be called directly by the user, but must be called by the GC.
         *
         * Note that since Java does not require the GC to call finalize() at all
         * it is recommended to not wrap any RAII objects that could lock or unlock
         * resources that are system wide.
         */
        ~SubClass2() {
            AllogenPInvoke.Destructor(Pointer);
        }

        /**
         * Calls the C++ doInSubclass2() native method
         */
        public virtual void DoInSubclass2() {
            AllogenPInvoke.DoInSubclass2(Pointer);
        }

        /**
         * Calls the C++ getName() native method
         */
        public override string GetName() {
            return AllogenPInvoke.GetName(Pointer);
        }

        /**
         * Calls the C++ fromNonvirtualBase() native method
         */
        public override void FromNonvirtualBase() {
            AllogenPInvoke.FromNonvirtualBase(Pointer);
        }

        private struct AllogenPInvoke {
            ///
            /// The native Interop library name
            ///
            #if DEBUG
            private const string LibraryName = "d.dll";
            #else
            private const string LibraryName = ".dll";
            #endif

            [DllImport(LibraryName,
                EntryPoint = "Allogen_Example_Inheritance_SubClass2_Constructor",
                CallingConvention = CallingConvention.StdCall)]
            public static extern IntPtr Constructor();

            [DllImport(LibraryName,
                EntryPoint = "Allogen_Example_Inheritance_SubClass2_Destructor",
                CallingConvention = CallingConvention.StdCall)]
            public static extern void Destructor(IntPtr pointer);

            [DllImport(LibraryName,
                EntryPoint = "Allogen_Example_Inheritance_SubClass2_doInSubclass2",
                CallingConvention = CallingConvention.StdCall,
                CharSet=CharSet.Ansi)]

            public static extern void DoInSubclass2(
                IntPtr pointer
            );

            [DllImport(LibraryName,
                EntryPoint = "Allogen_Example_Inheritance_SubClass2_getName",
                CallingConvention = CallingConvention.StdCall,
                CharSet=CharSet.Ansi)]
            [return: MarshalAs(UnmanagedType.BStr)]
            public static extern string GetName(
                IntPtr pointer
            );

            [DllImport(LibraryName,
                EntryPoint = "Allogen_Example_Inheritance_SubClass2_fromNonvirtualBase",
                CallingConvention = CallingConvention.StdCall,
                CharSet=CharSet.Ansi)]

            public static extern void FromNonvirtualBase(
                IntPtr pointer
            );

        }

        public new class Marshaller : ICustomMarshaler
        {
            public void CleanUpManagedData(object managedObj)
            {

            }

            public void CleanUpNativeData(IntPtr nativeData)
            {

            }

            public int GetNativeDataSize()
            {
                return IntPtr.Size;
            }

            public IntPtr MarshalManagedToNative(object managedObj)
            {
                return ((SubClass2) managedObj)?.Pointer ?? IntPtr.Zero;
            }

            public object MarshalNativeToManaged(IntPtr nativeData)
            {
                return nativeData.ToInt64() == 0 ? null : new SubClass2(nativeData);
            }

            private static readonly Marshaller Shared = new Marshaller();

            public static ICustomMarshaler GetInstance(string cookie)
            {
                return Shared;
            }
        }
    }
}


text:
import pygame
from pygame.sprite import Sprite

class Ship(Sprite):
    def __init__(self, ai_settings, screen):
        """ 初始化飞船并设置其初始位置 """
        super().__init__()
        self.screen = screen
        self.ai_settings = ai_settings

        # 加载飞船图像并获取其外接矩形
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # 将每艘新飞船放在屏幕底部中央
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        # 在飞船的属性center中存储小数值
        self.center = float(self.rect.centerx)

        # 移动标志
        self.moving_right = False
        self.moving_left = False

    def update(self):
        """ 根据移动标志调整飞船位置 """
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.center -= self.ai_settings.ship_speed_factor

        self.rect.centerx = self.center

    def blitme(self):
        """ 在指定位置绘制飞船 """
        self.screen.blit(self.image, self.rect)

    def center_ship(self):
        """ 重置ship位置 """
        self.center = self.screen_rect.centerx
        # self.rect.centerx = self.center


text:
Example code of a calendar with JsComponent and Greedo

## Using:
- Browserify
- JsComponent
- Greedo
- Moment
- Gulp
- Jasmine and Karma
- jQuery

## Compile:
- npm install
- gulp build

## TODO
- Jasmine tests are broken due to Browserify


text:
"""
Directory structure for a Python project

1. Modules
Every .py file IS A MODULE

2. Packages
3. Directory Structure
"""

import math
import sys
import lib.demo as demo

demo.hello()


text:
/**
 *
 */
package rx.internal.subscriptions;


text:
NS_ASSUME_NONNULL_BEGIN

@implementation WikipediaAppUtils

+ (NSString *)appVersion {
    return [[NSBundle mainBundle] wmf_versionForCurrentBundleIdentifier];
}

+ (NSString *)bundleID {
    return [[NSBundle mainBundle] wmf_bundleIdentifier];
}

+ (NSString *)formFactor {
    UIUserInterfaceIdiom ff = UI_USER_INTERFACE_IDIOM();
    // We'll break; on each case, just to follow good form.
    switch (ff) {
        case UIUserInterfaceIdiomPad:
            return @"Tablet";
            break;

        case UIUserInterfaceIdiomPhone:
            return @"Phone";
            break;

        default:
            return @"Other";
            break;
    }
}

+ (NSString *)versionedUserAgent {
    UIDevice *d = [UIDevice currentDevice];
    return [NSString stringWithFormat:@"WikipediaApp/%@ (%@ %@; %@)",
                                      [[NSBundle mainBundle] wmf_debugVersion],
                                      [d systemName],
                                      [d systemVersion],
                                      [self formFactor]];
}

static WMFAssetsFile *_Nullable languageFile = nil;

+ (NSString *)languageNameForCode:(NSString *)code {
    if (!languageFile) {
        languageFile = [[WMFAssetsFile alloc] initWithFileType:WMFAssetsFileTypeLanguages];
    }

    return [languageFile.array wmf_match:^BOOL(NSDictionary *obj) {
        return [obj[@"code"] isEqualToString:code];
    }][@"name"];
}

+ (NSString *)assetsPath {
    return [[NSBundle wmf] pathForResource:@"assets" ofType:nil];
}

@end

NS_ASSUME_NONNULL_END


text:
package org.n52.geofeed.feed.geo.simple;

import org.n52.geofeed.exception.MalformedGeoElementExecption;
import org.n52.geofeed.feed.geo.BaseGeoFeedElement;
import org.n52.geofeed.feed.geo.IPolygon;
import org.xml.sax.Attributes;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Polygon;

/**
 *
 * @author Arne de Wall <a.dewall@52North.org>
 *
 */
public class GeoRSSPolygon extends BaseGeoFeedElement implements IPolygon{

    public GeoRSSPolygon(String name, String uri, Attributes attibutes) {
        super(name, uri, attibutes);
    }

    @Override
    protected void parseGeometry() throws MalformedGeoElementExecption {
        String[] coordStrings = getElement(POLYGON).getContentString().split(" ");
        if(coordStrings.length%2 != 0)
            throw new MalformedGeoElementExecption(POLYGON);

        Coordinate[] coordinates = new Coordinate[coordStrings.length/2];
        for(int i = 0, j = 0; i < coordStrings.length / 2; i+=2, j++){
            coordinates[j] = new Coordinate(Double.parseDouble(coordStrings[i]),
                    Double.parseDouble(coordStrings[i+1]));
        }

        geometry = factory.createPolygon(factory.createLinearRing(coordinates), null);
    }

    @Override
    public Polygon getPolygon() {
        return (Polygon) getGeometry();
    }

}


text:
package androidx.leanback.leanbackshowcase.models;

import com.google.gson.annotations.SerializedName;

import java.util.List;

import androidx.leanback.leanbackshowcase.R;

/**
 * The video card data structure used to hold the fields of each video card fetched from the
 * url: {@link R.string.videos_url}
 */
public class VideoCard extends Card {

    @SerializedName("sources") private List<String> mVideoSources = null;
    @SerializedName("background") private String mBackgroundUrl = "";
    @SerializedName("studio") private String mStudio = "";

    public VideoCard() {
        super();
        setType(Type.VIDEO_GRID);
    }

    public List<String> getVideoSources() {
        return mVideoSources;
    }

    public void setVideoSources(List<String> sources) {
        mVideoSources = sources;
    }

    public String getBackground() {
        return mBackgroundUrl;
    }

    public void setBackground(String background) {
        mBackgroundUrl = background;
    }

    public String getStudio() {
        return mStudio;
    }

    public void setStudio(String studio) {
        mStudio = studio;
    }
}


text:
namespace ChampsRoom.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class UserAddEmail : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.AspNetUsers", "Email", c => c.String());
        }

        public override void Down()
        {
            DropColumn("dbo.AspNetUsers", "Email");
        }
    }
}


text:
<?php

/**
 * Authentication adapter for Phabricator OAuth2.
 */
final class PhutilPhabricatorAuthAdapter extends PhutilOAuthAuthAdapter {

  private $phabricatorBaseURI;
  private $adapterDomain;

  public function setPhabricatorBaseURI($uri) {
    $this->phabricatorBaseURI = $uri;
    return $this;
  }

  public function getPhabricatorBaseURI() {
    return $this->phabricatorBaseURI;
  }

  public function getAdapterDomain() {
    return $this->adapterDomain;
  }

  public function setAdapterDomain($domain) {
    $this->adapterDomain = $domain;
    return $this;
  }

  public function getAdapterType() {
    return 'phabricator';
  }

  public function getAccountID() {
    return $this->getOAuthAccountData('phid');
  }

  public function getAccountEmail() {
    return $this->getOAuthAccountData('primaryEmail');
  }

  public function getAccountName() {
    return $this->getOAuthAccountData('userName');
  }

  public function getAccountImageURI() {
    return $this->getOAuthAccountData('image');
  }

  public function getAccountURI() {
    return $this->getOAuthAccountData('uri');
  }

  public function getAccountRealName() {
    return $this->getOAuthAccountData('realName');
  }

  protected function getAuthenticateBaseURI() {
    return $this->getPhabricatorURI('oauthserver/auth/');
  }

  protected function getTokenBaseURI() {
    return $this->getPhabricatorURI('oauthserver/token/');
  }

  public function getScope() {
    return '';
  }

  public function getExtraAuthenticateParameters() {
    return array(
      'response_type' => 'code',
    );
  }

  public function getExtraTokenParameters() {
    return array(
      'grant_type' => 'authorization_code',
    );
  }

  protected function loadOAuthAccountData() {
    $uri = id(new PhutilURI($this->getPhabricatorURI('api/user.whoami')))
      ->replaceQueryParam('access_token', $this->getAccessToken());
    list($body) = id(new HTTPSFuture($uri))->resolvex();

    try {
      $data = phutil_json_decode($body);
      return $data['result'];
    } catch (PhutilJSONParserException $ex) {
      throw new Exception(
        pht(
          'Expected valid JSON response from "user.whoami" request.'),
        $ex);
    }
  }

  private function getPhabricatorURI($path) {
    return rtrim($this->phabricatorBaseURI, '/').'/'.ltrim($path, '/');
  }

}