text:
/* --------------------------------------------------------------------------------------------
 * Includes code from typescript-sublime-plugin project, obtained from
 * https://github.com/Microsoft/TypeScript-Sublime-Plugin/blob/master/TypeScript%20Indent.tmPreferences
 * ------------------------------------------------------------------------------------------ */

import * as vscode from 'vscode';
import { DiagnosticKind } from './features/diagnostics';
import FileConfigurationManager from './features/fileConfigurationManager';
import LanguageProvider from './languageProvider';
import * as Proto from './protocol';
import * as PConst from './protocol.const';
import TypeScriptServiceClient from './typescriptServiceClient';
import API from './utils/api';
import { CommandManager } from './utils/commandManager';
import { Disposable } from './utils/dispose';
import { LanguageDescription, DiagnosticLanguage } from './utils/languageDescription';
import LogDirectoryProvider from './utils/logDirectoryProvider';
import { TypeScriptServerPlugin } from './utils/plugins';
import * as typeConverters from './utils/typeConverters';
import TypingsStatus, { AtaProgressReporter } from './utils/typingsStatus';
import VersionStatus from './utils/versionStatus';

// Style check diagnostics that can be reported as warnings
const styleCheckDiagnostics = [
	6133, 	// variable is declared but never used
	6138, 	// property is declared but its value is never read
	7027,	// unreachable code detected
	7028,	// unused label
	7029,	// fall through case in switch
	7030	// not all code paths return a value
];

export default class TypeScriptServiceClientHost extends Disposable {
	private readonly typingsStatus: TypingsStatus;
	private readonly client: TypeScriptServiceClient;
	private readonly languages: LanguageProvider[] = [];
	private readonly languagePerId = new Map<string, LanguageProvider>();
	private readonly versionStatus: VersionStatus;
	private readonly fileConfigurationManager: FileConfigurationManager;

	private reportStyleCheckAsWarnings: boolean = true;

	constructor(
		descriptions: LanguageDescription[],
		workspaceState: vscode.Memento,
		plugins: TypeScriptServerPlugin[],
		private readonly commandManager: CommandManager,
		logDirectoryProvider: LogDirectoryProvider
	) {
		super();
		const handleProjectCreateOrDelete = () => {
			this.client.executeWithoutWaitingForResponse('reloadProjects', null);
			this.triggerAllDiagnostics();
		};
		const handleProjectChange = () => {
			setTimeout(() => {
				this.triggerAllDiagnostics();
			}, 1500);
		};
		const configFileWatcher = this._register(vscode.workspace.createFileSystemWatcher('**/[tj]sconfig.json'));
		configFileWatcher.onDidCreate(handleProjectCreateOrDelete, this, this._disposables);
		configFileWatcher.onDidDelete(handleProjectCreateOrDelete, this, this._disposables);
		configFileWatcher.onDidChange(handleProjectChange, this, this._disposables);

		const allModeIds = this.getAllModeIds(descriptions);
		this.client = this._register(new TypeScriptServiceClient(
			workspaceState,
			version => this.versionStatus.onDidChangeTypeScriptVersion(version),
			plugins,
			logDirectoryProvider,
			allModeIds));

		this.client.onDiagnosticsReceived(({ kind, resource, diagnostics }) => {
			this.diagnosticsReceived(kind, resource, diagnostics);
		}, null, this._disposables);

		this.client.onConfigDiagnosticsReceived(diag => this.configFileDiagnosticsReceived(diag), null, this._disposables);
		this.client.onResendModelsRequested(() => this.populateService(), null, this._disposables);

		this.versionStatus = this._register(new VersionStatus(resource => this.client.toPath(resource)));

		this._register(new AtaProgressReporter(this.client));
		this.typingsStatus = this._register(new TypingsStatus(this.client));
		this.fileConfigurationManager = this._register(new FileConfigurationManager(this.client));

		for (const description of descriptions) {
			const manager = new LanguageProvider(this.client, description, this.commandManager, this.client.telemetryReporter, this.typingsStatus, this.fileConfigurationManager);
			this.languages.push(manager);
			this._register(manager);
			this.languagePerId.set(description.id, manager);
		}

		import('./features/updatePathsOnRename').then(module =>
			this._register(module.register(this.client, this.fileConfigurationManager, uri => this.handles(uri))));

		import('./features/workspaceSymbols').then(module =>
			this._register(module.register(this.client, allModeIds)));

		this.client.ensureServiceStarted();
		this.client.onReady(() => {
			if (this.client.apiVersion.lt(API.v230)) {
				return;
			}

			const languages = new Set<string>();
			for (const plugin of plugins) {
				for (const language of plugin.languages) {
					languages.add(language);
				}
			}
			if (languages.size) {
				const description: LanguageDescription = {
					id: 'typescript-plugins',
					modeIds: Array.from(languages.values()),
					diagnosticSource: 'ts-plugin',
					diagnosticLanguage: DiagnosticLanguage.TypeScript,
					diagnosticOwner: 'typescript',
					isExternal: true
				};
				const manager = new LanguageProvider(this.client, description, this.commandManager, this.client.telemetryReporter, this.typingsStatus, this.fileConfigurationManager);
				this.languages.push(manager);
				this._register(manager);
				this.languagePerId.set(description.id, manager);
			}
		});

		this.client.onTsServerStarted(() => {
			this.triggerAllDiagnostics();
		});

		vscode.workspace.onDidChangeConfiguration(this.configurationChanged, this, this._disposables);
		this.configurationChanged();
	}

	private getAllModeIds(descriptions: LanguageDescription[]) {
		const allModeIds: string[] = [];
		for (const description of descriptions) {
			allModeIds.push(...description.modeIds);
		}
		return allModeIds;
	}

	public get serviceClient(): TypeScriptServiceClient {
		return this.client;
	}

	public reloadProjects(): void {
		this.client.executeWithoutWaitingForResponse('reloadProjects', null);
		this.triggerAllDiagnostics();
	}

	public async handles(resource: vscode.Uri): Promise<boolean> {
		const provider = await this.findLanguage(resource);
		if (provider) {
			return true;
		}
		return this.client.bufferSyncSupport.handles(resource);
	}

	private configurationChanged(): void {
		const typescriptConfig = vscode.workspace.getConfiguration('typescript');

		this.reportStyleCheckAsWarnings = typescriptConfig.get('reportStyleChecksAsWarnings', true);
	}

	private async findLanguage(resource: vscode.Uri): Promise<LanguageProvider | undefined> {
		try {
			const doc = await vscode.workspace.openTextDocument(resource);
			return this.languages.find(language => language.handles(resource, doc));
		} catch {
			return undefined;
		}
	}

	private triggerAllDiagnostics() {
		for (const language of this.languagePerId.values()) {
			language.triggerAllDiagnostics();
		}
	}

	private populateService(): void {
		this.fileConfigurationManager.reset();
		this.client.bufferSyncSupport.reOpenDocuments();
		this.client.bufferSyncSupport.requestAllDiagnostics();

		// See https://github.com/Microsoft/TypeScript/issues/5530
		vscode.workspace.saveAll(false).then(() => {
			for (const language of this.languagePerId.values()) {
				language.reInitialize();
			}
		});
	}

	private async diagnosticsReceived(
		kind: DiagnosticKind,
		resource: vscode.Uri,
		diagnostics: Proto.Diagnostic[]
	): Promise<void> {
		const language = await this.findLanguage(resource);
		if (language) {
			language.diagnosticsReceived(
				kind,
				resource,
				this.createMarkerDatas(diagnostics, language.diagnosticSource));
		}
	}

	private configFileDiagnosticsReceived(event: Proto.ConfigFileDiagnosticEvent): void {
		// See https://github.com/Microsoft/TypeScript/issues/10384
		const body = event.body;
		if (!body || !body.diagnostics || !body.configFile) {
			return;
		}

		(this.findLanguage(this.client.toResource(body.configFile))).then(language => {
			if (!language) {
				return;
			}
			if (body.diagnostics.length === 0) {
				language.configFileDiagnosticsReceived(this.client.toResource(body.configFile), []);
			} else if (body.diagnostics.length >= 1) {
				vscode.workspace.openTextDocument(vscode.Uri.file(body.configFile)).then((document) => {
					let curly: [number, number, number] | undefined = undefined;
					let nonCurly: [number, number, number] | undefined = undefined;
					let diagnostic: vscode.Diagnostic;
					for (let index = 0; index < document.lineCount; index++) {
						const line = document.lineAt(index);
						const text = line.text;
						const firstNonWhitespaceCharacterIndex = line.firstNonWhitespaceCharacterIndex;
						if (firstNonWhitespaceCharacterIndex < text.length) {
							if (text.charAt(firstNonWhitespaceCharacterIndex) === '{') {
								curly = [index, firstNonWhitespaceCharacterIndex, firstNonWhitespaceCharacterIndex + 1];
								break;
							} else {
								const matches = /\s*([^\s]*)(?:\s*|$)/.exec(text.substr(firstNonWhitespaceCharacterIndex));
								if (matches && matches.length >= 1) {
									nonCurly = [index, firstNonWhitespaceCharacterIndex, firstNonWhitespaceCharacterIndex + matches[1].length];
								}
							}
						}
					}
					const match = curly || nonCurly;
					if (match) {
						diagnostic = new vscode.Diagnostic(new vscode.Range(match[0], match[1], match[0], match[2]), body.diagnostics[0].text);
					} else {
						diagnostic = new vscode.Diagnostic(new vscode.Range(0, 0, 0, 0), body.diagnostics[0].text);
					}
					if (diagnostic) {
						diagnostic.source = language.diagnosticSource;
						language.configFileDiagnosticsReceived(this.client.toResource(body.configFile), [diagnostic]);
					}
				}, _error => {
					language.configFileDiagnosticsReceived(this.client.toResource(body.configFile), [new vscode.Diagnostic(new vscode.Range(0, 0, 0, 0), body.diagnostics[0].text)]);
				});
			}
		});
	}

	private createMarkerDatas(
		diagnostics: Proto.Diagnostic[],
		source: string
	): (vscode.Diagnostic & { reportUnnecessary: any })[] {
		return diagnostics.map(tsDiag => this.tsDiagnosticToVsDiagnostic(tsDiag, source));
	}

	private tsDiagnosticToVsDiagnostic(diagnostic: Proto.Diagnostic, source: string): vscode.Diagnostic & { reportUnnecessary: any } {
		const { start, end, text } = diagnostic;
		const range = new vscode.Range(typeConverters.Position.fromLocation(start), typeConverters.Position.fromLocation(end));
		const converted = new vscode.Diagnostic(range, text);
		converted.severity = this.getDiagnosticSeverity(diagnostic);
		converted.source = diagnostic.source || source;
		if (diagnostic.code) {
			converted.code = diagnostic.code;
		}
		const relatedInformation = diagnostic.relatedInformation;
		if (relatedInformation) {
			converted.relatedInformation = relatedInformation.map((info: any) => {
				let span = info.span;
				if (!span) {
					return undefined;
				}
				return new vscode.DiagnosticRelatedInformation(typeConverters.Location.fromTextSpan(this.client.toResource(span.file), span), info.message);
			}).filter((x: any) => !!x) as vscode.DiagnosticRelatedInformation[];
		}
		if (diagnostic.reportsUnnecessary) {
			converted.tags = [vscode.DiagnosticTag.Unnecessary];
		}
		(converted as vscode.Diagnostic & { reportUnnecessary: any }).reportUnnecessary = diagnostic.reportsUnnecessary;
		return converted as vscode.Diagnostic & { reportUnnecessary: any };
	}

	private getDiagnosticSeverity(diagnostic: Proto.Diagnostic): vscode.DiagnosticSeverity {
		if (this.reportStyleCheckAsWarnings
			&& this.isStyleCheckDiagnostic(diagnostic.code)
			&& diagnostic.category === PConst.DiagnosticCategory.error
		) {
			return vscode.DiagnosticSeverity.Warning;
		}

		switch (diagnostic.category) {
			case PConst.DiagnosticCategory.error:
				return vscode.DiagnosticSeverity.Error;

			case PConst.DiagnosticCategory.warning:
				return vscode.DiagnosticSeverity.Warning;

			case PConst.DiagnosticCategory.suggestion:
				return vscode.DiagnosticSeverity.Hint;

			default:
				return vscode.DiagnosticSeverity.Error;
		}
	}

	private isStyleCheckDiagnostic(code: number | undefined): boolean {
		return code ? styleCheckDiagnostics.indexOf(code) !== -1 : false;
	}
}


text:
layout: page
title: Eugene Wagner's 94th Birthday
date: 2016-05-24
author: Nicholas Robertson
tags: weekly links, java
status: published
summary: Donec tempus posuere sapien in gravida.
banner: images/banner/wedding.jpg
booking:
  startDate: 08/29/2017
  endDate: 08/31/2017
  ctyhocn: WLTSCHX
  groupCode: EW9B
published: true
---
Nunc nec vulputate diam. Etiam sit amet elit eu nibh mollis ultricies. Duis facilisis metus et efficitur sollicitudin. Donec sodales feugiat enim, non condimentum nisl ullamcorper sit amet. Proin tincidunt pharetra porttitor. Suspendisse non ligula eget metus molestie elementum. Curabitur fringilla nisl id purus cursus, at elementum nibh blandit. Nunc accumsan egestas elementum. Donec id condimentum nisi. Donec egestas dolor ipsum. Duis et elementum quam, at maximus massa. Maecenas tempus purus at convallis pharetra.

1 Donec placerat urna non neque semper, ac tempus neque tempor
1 Integer cursus quam eu velit congue malesuada
1 Morbi malesuada nunc ut tincidunt congue
1 Praesent suscipit lacus in ornare maximus.

Pellentesque rutrum nec leo id fermentum. Cras dapibus arcu quis elit pharetra tempor. Nam sagittis mi commodo pellentesque dignissim. Nunc ac fringilla justo, at tincidunt tellus. Sed in est vitae lectus varius ultrices quis eu augue. Nulla molestie commodo bibendum. Sed fermentum diam risus, sit amet laoreet nisl feugiat in. Donec rhoncus felis nec ante egestas finibus. Aenean eleifend nisi nec tellus lacinia faucibus.
Vivamus ornare, velit vel lacinia condimentum, risus leo lacinia mi, ac fringilla enim nunc sed diam. In dui neque, gravida ut ligula ac, euismod dictum enim. Suspendisse potenti. Phasellus posuere ex non quam vestibulum interdum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque efficitur porttitor magna, eget placerat velit pretium ut. Morbi porttitor velit mauris, id tempus metus pretium non. Aenean commodo, arcu nec vulputate luctus, velit urna dictum dolor, quis tempus risus libero commodo ante. Praesent eu tincidunt nibh, quis auctor mauris. Sed ac feugiat leo.

redpajama_set_name: RedPajamaGithub


text:
function [data info] = ft2mat(data)
info = rmfield(data,'trial');
data = reshape(cell2mat(data.trial),size(data.trial{1},1), size(data.trial{1},2), []);
return


text:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.zabonlinedb.data.AreaCode" table="V_AREA_CODE" dynamic-insert="false" dynamic-update="false">
        <id name="id" type="integer">
            <column name="ID"/>
            <generator class="assigned"/>
        </id>
        <property name="tagId" type="integer">
            <column name="TAG_ID"/>
        </property>
        <property name="caption" type="string">
            <column name="CAPTION" length="254" not-null="true"/>
        </property>
        <property name="description" type="string">
            <column name="DESCRIPTION" length="2000"/>
        </property>
        <property name="donotdelete" type="short">
            <column name="DONOTDELETE"/>
        </property>
        <property name="softdel" type="short">
            <column name="SOFTDEL"/>
        </property>
        <property name="creUser" type="string">
            <column name="CRE_USER" length="32" not-null="true"/>
        </property>
        <property name="creDate" type="date">
            <column name="CRE_DATE" length="8" not-null="true"/>
        </property>
        <property name="chgUser" type="string">
            <column name="CHG_USER" length="32"/>
        </property>
        <property name="chgDate" type="date">
            <column name="CHG_DATE" length="8"/>
        </property>
        <many-to-one name="country" class="com.zabonlinedb.data.Country" cascade="none">
            <column name="COUNTRY_ID"/>
        </many-to-one>
    </class>
</hibernate-mapping>


text:
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import configureStore from './store/configureStore'

import App from './components/App'
import Home from './components/Home'
import Foo from './components/Foo'
import Bar from './components/Bar'

const initialState = { items: { num: 0 } }
const store = configureStore(initialState)
const history = syncHistoryWithStore(hashHistory, store)

render(
  <Provider store={store}>
    <Router history={ history }>
      <Route path='/' component={App}>
        <IndexRoute component={Home}/>
        <Route path='/home' component={Home}/>
        <Route path='/foo' component={Foo}/>
        <Route path='/bar' component={Bar}/>
      </Route>
    </Router>
  </Provider>,
  document.querySelector('#app')
)


text:
This folder contains the Dockerfile and the commands required to build and
manage a container with a RabbitMQ server instance.

## Build the Container
Docker container is based on Ubuntu 16.04. To build the container run:
```
./bin/rabbit build
```

## Manage the Container
Once the container has been built, it is possible to run it, stop it, or ask for
the status, with:
```
./bin/rabbit start | stop | status
```
The `start` command will try to run the Docker container if this does't exist
yet, otherwise it will restart the existing one.

## Create a new Admin
RabbitMQ has a management web interface, with no default users enabled. To create
a user, simply run:
```
./bin/rabbit add_user my_username my_password
```
After that, navigate to http://localhost:15672/ and use the newly created
credentials to login.

## List of Available Commands

* `build`: Build the Docker image
* `start`: Run RabbitMQ on http://localhost:15672/
* `stop`: Stop RabbitMQ
* `status`: Verify the status of RabbitMQ server
* `add_user <USR> <PWD>`: Add a new <USR> with <PWD> to the RabbitMQ management console


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace XenAPI
{
    /// <summary>
    /// Represents a patch stored on a server
    /// First published in XenServer 4.0.
    /// </summary>
    public partial class Host_patch : XenObject<Host_patch>
    {
        public Host_patch()
        {
        }

        public Host_patch(string uuid,
            string name_label,
            string name_description,
            string version,
            XenRef<Host> host,
            bool applied,
            DateTime timestamp_applied,
            long size,
            XenRef<Pool_patch> pool_patch,
            Dictionary<string, string> other_config)
        {
            this.uuid = uuid;
            this.name_label = name_label;
            this.name_description = name_description;
            this.version = version;
            this.host = host;
            this.applied = applied;
            this.timestamp_applied = timestamp_applied;
            this.size = size;
            this.pool_patch = pool_patch;
            this.other_config = other_config;
        }

        /// <summary>
        /// Creates a new Host_patch from a Proxy_Host_patch.
        /// </summary>
        /// <param name="proxy"></param>
        public Host_patch(Proxy_Host_patch proxy)
        {
            this.UpdateFromProxy(proxy);
        }

        /// <summary>
        /// Updates each field of this instance with the value of
        /// the corresponding field of a given Host_patch.
        /// </summary>
        public override void UpdateFrom(Host_patch update)
        {
            uuid = update.uuid;
            name_label = update.name_label;
            name_description = update.name_description;
            version = update.version;
            host = update.host;
            applied = update.applied;
            timestamp_applied = update.timestamp_applied;
            size = update.size;
            pool_patch = update.pool_patch;
            other_config = update.other_config;
        }

        internal void UpdateFromProxy(Proxy_Host_patch proxy)
        {
            uuid = proxy.uuid == null ? null : (string)proxy.uuid;
            name_label = proxy.name_label == null ? null : (string)proxy.name_label;
            name_description = proxy.name_description == null ? null : (string)proxy.name_description;
            version = proxy.version == null ? null : (string)proxy.version;
            host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
            applied = (bool)proxy.applied;
            timestamp_applied = proxy.timestamp_applied;
            size = proxy.size == null ? 0 : long.Parse((string)proxy.size);
            pool_patch = proxy.pool_patch == null ? null : XenRef<Pool_patch>.Create(proxy.pool_patch);
            other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
        }

        public Proxy_Host_patch ToProxy()
        {
            Proxy_Host_patch result_ = new Proxy_Host_patch();
            result_.uuid = uuid ?? "";
            result_.name_label = name_label ?? "";
            result_.name_description = name_description ?? "";
            result_.version = version ?? "";
            result_.host = host ?? "";
            result_.applied = applied;
            result_.timestamp_applied = timestamp_applied;
            result_.size = size.ToString();
            result_.pool_patch = pool_patch ?? "";
            result_.other_config = Maps.convert_to_proxy_string_string(other_config);
            return result_;
        }

        /// <summary>
        /// Creates a new Host_patch from a Hashtable.
        /// Note that the fields not contained in the Hashtable
        /// will be created with their default values.
        /// </summary>
        /// <param name="table"></param>
        public Host_patch(Hashtable table) : this()
        {
            UpdateFrom(table);
        }

        /// <summary>
        /// Given a Hashtable with field-value pairs, it updates the fields of this Host_patch
        /// with the values listed in the Hashtable. Note that only the fields contained
        /// in the Hashtable will be updated and the rest will remain the same.
        /// </summary>
        /// <param name="table"></param>
        public void UpdateFrom(Hashtable table)
        {
            if (table.ContainsKey("uuid"))
                uuid = Marshalling.ParseString(table, "uuid");
            if (table.ContainsKey("name_label"))
                name_label = Marshalling.ParseString(table, "name_label");
            if (table.ContainsKey("name_description"))
                name_description = Marshalling.ParseString(table, "name_description");
            if (table.ContainsKey("version"))
                version = Marshalling.ParseString(table, "version");
            if (table.ContainsKey("host"))
                host = Marshalling.ParseRef<Host>(table, "host");
            if (table.ContainsKey("applied"))
                applied = Marshalling.ParseBool(table, "applied");
            if (table.ContainsKey("timestamp_applied"))
                timestamp_applied = Marshalling.ParseDateTime(table, "timestamp_applied");
            if (table.ContainsKey("size"))
                size = Marshalling.ParseLong(table, "size");
            if (table.ContainsKey("pool_patch"))
                pool_patch = Marshalling.ParseRef<Pool_patch>(table, "pool_patch");
            if (table.ContainsKey("other_config"))
                other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
        }

        public bool DeepEquals(Host_patch other)
        {
            if (ReferenceEquals(null, other))
                return false;
            if (ReferenceEquals(this, other))
                return true;

            return Helper.AreEqual2(this._uuid, other._uuid) &&
                Helper.AreEqual2(this._name_label, other._name_label) &&
                Helper.AreEqual2(this._name_description, other._name_description) &&
                Helper.AreEqual2(this._version, other._version) &&
                Helper.AreEqual2(this._host, other._host) &&
                Helper.AreEqual2(this._applied, other._applied) &&
                Helper.AreEqual2(this._timestamp_applied, other._timestamp_applied) &&
                Helper.AreEqual2(this._size, other._size) &&
                Helper.AreEqual2(this._pool_patch, other._pool_patch) &&
                Helper.AreEqual2(this._other_config, other._other_config);
        }

        internal static List<Host_patch> ProxyArrayToObjectList(Proxy_Host_patch[] input)
        {
            var result = new List<Host_patch>();
            foreach (var item in input)
                result.Add(new Host_patch(item));

            return result;
        }

        public override string SaveChanges(Session session, string opaqueRef, Host_patch server)
        {
            if (opaqueRef == null)
            {
                System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
                return "";
            }
            else
            {
                if (!Helper.AreEqual2(_other_config, server._other_config))
                {
                    Host_patch.set_other_config(session, opaqueRef, _other_config);
                }

                return null;
            }
        }
        /// <summary>
        /// Get a record containing the current state of the given host_patch.
        /// First published in XenServer 4.0.
        /// Deprecated since XenServer 7.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        [Deprecated("XenServer 7.1")]
        public static Host_patch get_record(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_record(session.opaque_ref, _host_patch);
            else
                return new Host_patch((Proxy_Host_patch)session.proxy.host_patch_get_record(session.opaque_ref, _host_patch ?? "").parse());
        }

        /// <summary>
        /// Get a reference to the host_patch instance with the specified UUID.
        /// First published in XenServer 4.0.
        /// Deprecated since XenServer 7.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_uuid">UUID of object to return</param>
        [Deprecated("XenServer 7.1")]
        public static XenRef<Host_patch> get_by_uuid(Session session, string _uuid)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_by_uuid(session.opaque_ref, _uuid);
            else
                return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
        }

        /// <summary>
        /// Get all the host_patch instances with the given label.
        /// First published in XenServer 4.0.
        /// Deprecated since XenServer 7.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_label">label of object to return</param>
        [Deprecated("XenServer 7.1")]
        public static List<XenRef<Host_patch>> get_by_name_label(Session session, string _label)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_by_name_label(session.opaque_ref, _label);
            else
                return XenRef<Host_patch>.Create(session.proxy.host_patch_get_by_name_label(session.opaque_ref, _label ?? "").parse());
        }

        /// <summary>
        /// Get the uuid field of the given host_patch.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static string get_uuid(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_uuid(session.opaque_ref, _host_patch);
            else
                return (string)session.proxy.host_patch_get_uuid(session.opaque_ref, _host_patch ?? "").parse();
        }

        /// <summary>
        /// Get the name/label field of the given host_patch.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static string get_name_label(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_name_label(session.opaque_ref, _host_patch);
            else
                return (string)session.proxy.host_patch_get_name_label(session.opaque_ref, _host_patch ?? "").parse();
        }

        /// <summary>
        /// Get the name/description field of the given host_patch.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static string get_name_description(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_name_description(session.opaque_ref, _host_patch);
            else
                return (string)session.proxy.host_patch_get_name_description(session.opaque_ref, _host_patch ?? "").parse();
        }

        /// <summary>
        /// Get the version field of the given host_patch.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static string get_version(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_version(session.opaque_ref, _host_patch);
            else
                return (string)session.proxy.host_patch_get_version(session.opaque_ref, _host_patch ?? "").parse();
        }

        /// <summary>
        /// Get the host field of the given host_patch.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static XenRef<Host> get_host(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_host(session.opaque_ref, _host_patch);
            else
                return XenRef<Host>.Create(session.proxy.host_patch_get_host(session.opaque_ref, _host_patch ?? "").parse());
        }

        /// <summary>
        /// Get the applied field of the given host_patch.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static bool get_applied(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_applied(session.opaque_ref, _host_patch);
            else
                return (bool)session.proxy.host_patch_get_applied(session.opaque_ref, _host_patch ?? "").parse();
        }

        /// <summary>
        /// Get the timestamp_applied field of the given host_patch.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static DateTime get_timestamp_applied(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_timestamp_applied(session.opaque_ref, _host_patch);
            else
                return session.proxy.host_patch_get_timestamp_applied(session.opaque_ref, _host_patch ?? "").parse();
        }

        /// <summary>
        /// Get the size field of the given host_patch.
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static long get_size(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_size(session.opaque_ref, _host_patch);
            else
                return long.Parse((string)session.proxy.host_patch_get_size(session.opaque_ref, _host_patch ?? "").parse());
        }

        /// <summary>
        /// Get the pool_patch field of the given host_patch.
        /// First published in XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static XenRef<Pool_patch> get_pool_patch(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_pool_patch(session.opaque_ref, _host_patch);
            else
                return XenRef<Pool_patch>.Create(session.proxy.host_patch_get_pool_patch(session.opaque_ref, _host_patch ?? "").parse());
        }

        /// <summary>
        /// Get the other_config field of the given host_patch.
        /// First published in XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        public static Dictionary<string, string> get_other_config(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_other_config(session.opaque_ref, _host_patch);
            else
                return Maps.convert_from_proxy_string_string(session.proxy.host_patch_get_other_config(session.opaque_ref, _host_patch ?? "").parse());
        }

        /// <summary>
        /// Set the other_config field of the given host_patch.
        /// First published in XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        /// <param name="_other_config">New value to set</param>
        public static void set_other_config(Session session, string _host_patch, Dictionary<string, string> _other_config)
        {
            if (session.JsonRpcClient != null)
                session.JsonRpcClient.host_patch_set_other_config(session.opaque_ref, _host_patch, _other_config);
            else
                session.proxy.host_patch_set_other_config(session.opaque_ref, _host_patch ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
        }

        /// <summary>
        /// Add the given key-value pair to the other_config field of the given host_patch.
        /// First published in XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        /// <param name="_key">Key to add</param>
        /// <param name="_value">Value to add</param>
        public static void add_to_other_config(Session session, string _host_patch, string _key, string _value)
        {
            if (session.JsonRpcClient != null)
                session.JsonRpcClient.host_patch_add_to_other_config(session.opaque_ref, _host_patch, _key, _value);
            else
                session.proxy.host_patch_add_to_other_config(session.opaque_ref, _host_patch ?? "", _key ?? "", _value ?? "").parse();
        }

        /// <summary>
        /// Remove the given key and its corresponding value from the other_config field of the given host_patch.  If the key is not in that Map, then do nothing.
        /// First published in XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        /// <param name="_key">Key to remove</param>
        public static void remove_from_other_config(Session session, string _host_patch, string _key)
        {
            if (session.JsonRpcClient != null)
                session.JsonRpcClient.host_patch_remove_from_other_config(session.opaque_ref, _host_patch, _key);
            else
                session.proxy.host_patch_remove_from_other_config(session.opaque_ref, _host_patch ?? "", _key ?? "").parse();
        }

        /// <summary>
        /// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
        /// First published in XenServer 4.0.
        /// Deprecated since XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        [Deprecated("XenServer 4.1")]
        public static void destroy(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                session.JsonRpcClient.host_patch_destroy(session.opaque_ref, _host_patch);
            else
                session.proxy.host_patch_destroy(session.opaque_ref, _host_patch ?? "").parse();
        }

        /// <summary>
        /// Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch
        /// First published in XenServer 4.0.
        /// Deprecated since XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        [Deprecated("XenServer 4.1")]
        public static XenRef<Task> async_destroy(Session session, string _host_patch)
        {
          if (session.JsonRpcClient != null)
              return session.JsonRpcClient.async_host_patch_destroy(session.opaque_ref, _host_patch);
          else
              return XenRef<Task>.Create(session.proxy.async_host_patch_destroy(session.opaque_ref, _host_patch ?? "").parse());
        }

        /// <summary>
        /// Apply the selected patch and return its output
        /// First published in XenServer 4.0.
        /// Deprecated since XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        [Deprecated("XenServer 4.1")]
        public static string apply(Session session, string _host_patch)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_apply(session.opaque_ref, _host_patch);
            else
                return (string)session.proxy.host_patch_apply(session.opaque_ref, _host_patch ?? "").parse();
        }

        /// <summary>
        /// Apply the selected patch and return its output
        /// First published in XenServer 4.0.
        /// Deprecated since XenServer 4.1.
        /// </summary>
        /// <param name="session">The session</param>
        /// <param name="_host_patch">The opaque_ref of the given host_patch</param>
        [Deprecated("XenServer 4.1")]
        public static XenRef<Task> async_apply(Session session, string _host_patch)
        {
          if (session.JsonRpcClient != null)
              return session.JsonRpcClient.async_host_patch_apply(session.opaque_ref, _host_patch);
          else
              return XenRef<Task>.Create(session.proxy.async_host_patch_apply(session.opaque_ref, _host_patch ?? "").parse());
        }

        /// <summary>
        /// Return a list of all the host_patchs known to the system.
        /// First published in XenServer 4.0.
        /// Deprecated since XenServer 7.1.
        /// </summary>
        /// <param name="session">The session</param>
        [Deprecated("XenServer 7.1")]
        public static List<XenRef<Host_patch>> get_all(Session session)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_all(session.opaque_ref);
            else
                return XenRef<Host_patch>.Create(session.proxy.host_patch_get_all(session.opaque_ref).parse());
        }

        /// <summary>
        /// Get all the host_patch Records at once, in a single XML RPC call
        /// First published in XenServer 4.0.
        /// </summary>
        /// <param name="session">The session</param>
        public static Dictionary<XenRef<Host_patch>, Host_patch> get_all_records(Session session)
        {
            if (session.JsonRpcClient != null)
                return session.JsonRpcClient.host_patch_get_all_records(session.opaque_ref);
            else
                return XenRef<Host_patch>.Create<Proxy_Host_patch>(session.proxy.host_patch_get_all_records(session.opaque_ref).parse());
        }

        /// <summary>
        /// Unique identifier/object reference
        /// </summary>
        public virtual string uuid
        {
            get { return _uuid; }
            set
            {
                if (!Helper.AreEqual(value, _uuid))
                {
                    _uuid = value;
                    Changed = true;
                    NotifyPropertyChanged("uuid");
                }
            }
        }
        private string _uuid = "";

        /// <summary>
        /// a human-readable name
        /// </summary>
        public virtual string name_label
        {
            get { return _name_label; }
            set
            {
                if (!Helper.AreEqual(value, _name_label))
                {
                    _name_label = value;
                    Changed = true;
                    NotifyPropertyChanged("name_label");
                }
            }
        }
        private string _name_label = "";

        /// <summary>
        /// a notes field containing human-readable description
        /// </summary>
        public virtual string name_description
        {
            get { return _name_description; }
            set
            {
                if (!Helper.AreEqual(value, _name_description))
                {
                    _name_description = value;
                    Changed = true;
                    NotifyPropertyChanged("name_description");
                }
            }
        }
        private string _name_description = "";

        /// <summary>
        /// Patch version number
        /// </summary>
        public virtual string version
        {
            get { return _version; }
            set
            {
                if (!Helper.AreEqual(value, _version))
                {
                    _version = value;
                    Changed = true;
                    NotifyPropertyChanged("version");
                }
            }
        }
        private string _version = "";

        /// <summary>
        /// Host the patch relates to
        /// </summary>
        [JsonConverter(typeof(XenRefConverter<Host>))]
        public virtual XenRef<Host> host
        {
            get { return _host; }
            set
            {
                if (!Helper.AreEqual(value, _host))
                {
                    _host = value;
                    Changed = true;
                    NotifyPropertyChanged("host");
                }
            }
        }
        private XenRef<Host> _host = new XenRef<Host>(Helper.NullOpaqueRef);

        /// <summary>
        /// True if the patch has been applied
        /// </summary>
        public virtual bool applied
        {
            get { return _applied; }
            set
            {
                if (!Helper.AreEqual(value, _applied))
                {
                    _applied = value;
                    Changed = true;
                    NotifyPropertyChanged("applied");
                }
            }
        }
        private bool _applied;

        /// <summary>
        /// Time the patch was applied
        /// </summary>
        [JsonConverter(typeof(XenDateTimeConverter))]
        public virtual DateTime timestamp_applied
        {
            get { return _timestamp_applied; }
            set
            {
                if (!Helper.AreEqual(value, _timestamp_applied))
                {
                    _timestamp_applied = value;
                    Changed = true;
                    NotifyPropertyChanged("timestamp_applied");
                }
            }
        }
        private DateTime _timestamp_applied;

        /// <summary>
        /// Size of the patch
        /// </summary>
        public virtual long size
        {
            get { return _size; }
            set
            {
                if (!Helper.AreEqual(value, _size))
                {
                    _size = value;
                    Changed = true;
                    NotifyPropertyChanged("size");
                }
            }
        }
        private long _size;

        /// <summary>
        /// The patch applied
        /// First published in XenServer 4.1.
        /// </summary>
        [JsonConverter(typeof(XenRefConverter<Pool_patch>))]
        public virtual XenRef<Pool_patch> pool_patch
        {
            get { return _pool_patch; }
            set
            {
                if (!Helper.AreEqual(value, _pool_patch))
                {
                    _pool_patch = value;
                    Changed = true;
                    NotifyPropertyChanged("pool_patch");
                }
            }
        }
        private XenRef<Pool_patch> _pool_patch = new XenRef<Pool_patch>(Helper.NullOpaqueRef);

        /// <summary>
        /// additional configuration
        /// First published in XenServer 4.1.
        /// </summary>
        [JsonConverter(typeof(StringStringMapConverter))]
        public virtual Dictionary<string, string> other_config
        {
            get { return _other_config; }
            set
            {
                if (!Helper.AreEqual(value, _other_config))
                {
                    _other_config = value;
                    Changed = true;
                    NotifyPropertyChanged("other_config");
                }
            }
        }
        private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
    }
}


text:
node-init
=========

Ready-to-go node project, including mongoose setup, user authentication, speed optimisation, basic routing, basic error handling, requirejs setup and build tasks.


text:
import * as React from 'react';
import PageHeader from '..';
import { pageHeaderTestkitFactory } from '../../../testkit';
import { pageHeaderTestkitFactory as pageHeaderEnzymeTestkitFactory } from '../../../testkit/enzyme';
import { pageHeaderTestkitFactory as pageHeaderPuppeteerTestkitFactory } from '../../../testkit/puppeteer';
import * as enzyme from 'enzyme';
import * as puppeteer from 'puppeteer';

function PageHeaderWithMandatoryProps() {
  return <PageHeader />;
}

function PageHeaderWithAllProps() {
  return (
    <PageHeader
      actionsBar={<div />}
      breadcrumbs={<div />}
      className="cls"
      dataHook="hook"
      hasBackgroundImage
      minimized
      onBackClicked={_ev => {}}
      showBackButton
      subtitle={<div />}
      title={<div />}
    />
  );
}

function PageHeaderWithRenderFunctions() {
  return (
    <PageHeader
      actionsBar={({ hasBackgroundImage, minimized }) => {}}
      breadcrumbs={<div />}
      className="cls"
      dataHook="hook"
      hasBackgroundImage
      minimized
      onBackClicked={_ev => {}}
      showBackButton
      subtitle={<div />}
      title={_minimized => {}}
    />
  );
}

async function testkits() {
  const testkit = pageHeaderTestkitFactory({
    dataHook: 'hook',
    wrapper: document.createElement('div'),
  });

  const enzymeTestkit = pageHeaderEnzymeTestkitFactory({
    dataHook: 'hook',
    wrapper: enzyme.mount(<div />),
  });

  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  const puppeteerTestkit = await pageHeaderPuppeteerTestkitFactory({
    dataHook: 'hook',
    page,
  });
}


text:
package uk.co.jamesmcguigan.patterns.creational.lazyinitialization;

import java.util.HashMap;
import java.util.Map;

enum FruitType {
    none,
    apple,
    banana,
}

public class Fruit {

    private static Map<FruitType, Fruit> types = new HashMap<FruitType, Fruit>();

    /**
     * Using a private constructor to force the use of the factory method.
     * @param type
     */
    private Fruit(final FruitType type) {
    }

    /**
     * Lazy Factory method, gets the Fruit instance associated with a certain
     * type. Instantiates new ones as needed.
     * @param type Any allowed fruit type, e.g. APPLE
     * @return The Fruit instance associated with that type.
     */
    public static Fruit getFruitByTypeName(final FruitType type) {
        Fruit fruit;
        // This has concurrency issues.  Here the read to types is not synchronized,
        // so types.put and types.containsKey might be called at the same time.
        // Don't be surprised if the data is corrupted.
        if (!types.containsKey(type)) {
            // Lazy initialisation
            fruit = new Fruit(type);
            types.put(type, fruit);
        } else {
            // OK, it's available currently
            fruit = types.get(type);
        }

        return fruit;
    }

    /**
     * Lazy Factory method, gets the Fruit instance associated with a certain
     * type. Instantiates new ones as needed. Uses double-checked locking
     * pattern for using in highly concurrent environments.
     * @param type Any allowed fruit type, e.g. APPLE
     * @return The Fruit instance associated with that type.
     */
    public static Fruit getFruitByTypeNameHighConcurrentVersion(final FruitType type) {
        if (!types.containsKey(type)) {
            synchronized (types) {
                // Check again, after having acquired the lock to make sure
                // the instance was not created meanwhile by another thread
                if (!types.containsKey(type)) {
                    // Lazy initialisation
                    types.put(type, new Fruit(type));
                }
            }
        }

        return types.get(type);
    }

    /**
     * Displays all entered fruits.
     */
    public static void showAll() {
        if (types.size() > 0) {

            System.out.println("Number of instances made = " + types.size());

            for (Map.Entry<FruitType, Fruit> entry : types.entrySet()) {
                String fruit = entry.getKey().toString();
                fruit = Character.toUpperCase(fruit.charAt(0)) + fruit.substring(1);
                System.out.println(fruit);
            }

            System.out.println();
        }
    }
}


text:
package com.google.javascript.jscomp;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.javascript.jscomp.parsing.parser.util.format.SimpleFormat;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.regex.Pattern;

/**
 * Generates goog.exportSymbol for test functions, so they can be recognized
 * by the test runner, even if the code is compiled.
 *
 */
public class ExportTestFunctions implements CompilerPass {

  private static final Pattern TEST_FUNCTIONS_NAME_PATTERN =
      Pattern.compile(
          "^(?:((\\w+\\.)+prototype\\.||window\\.)*"
              + "(setUpPage|setUp|shouldRunTests|tearDown|tearDownPage|test[\\w\\$]+))$");

  private final AbstractCompiler compiler;
  private final String exportSymbolFunction;
  private final String exportPropertyFunction;

  /**
   * Creates a new export test functions compiler pass.
   * @param compiler
   * @param exportSymbolFunction The function name used to export symbols in JS.
   * @param exportPropertyFunction The function name used to export properties
   *     in JS.
   */
  ExportTestFunctions(AbstractCompiler compiler,
      String exportSymbolFunction, String exportPropertyFunction) {

    checkNotNull(compiler);
    this.compiler = compiler;
    this.exportSymbolFunction = exportSymbolFunction;
    this.exportPropertyFunction = exportPropertyFunction;
  }

  private class ExportTestFunctionsNodes extends NodeTraversal.AbstractShallowCallback {
    @Override
    public void visit(NodeTraversal t, Node n, Node parent) {
      if (parent == null) {
        return;
      }

      if (parent.isScript()) {
        if (NodeUtil.isFunctionDeclaration(n)) {
          // Check for a test function statement.
          String functionName = NodeUtil.getName(n);
          if (isTestFunction(functionName)) {
            exportTestFunctionAsSymbol(functionName, n, parent);
          }
        } else if (isNameDeclaredFunction(n)) {
          // Check for a test function expression.
          Node functionNode = n.getFirstFirstChild();
          String functionName = NodeUtil.getName(functionNode);
          if (isTestFunction(functionName)) {
            exportTestFunctionAsSymbol(functionName, n, parent);
          }
        } else if (isNameDeclaredClass(n)) {
          Node classNode = n.getFirstFirstChild();
          String className = NodeUtil.getName(classNode);
          exportClass(parent, classNode, className, n);
        } else if (n.isClass()) {
          exportClass(parent, n);
        }
      } else if (NodeUtil.isExprAssign(parent) && !n.getLastChild().isAssign()) {
        // Check for a test method assignment.
        Node grandparent = parent.getParent();
        if (grandparent != null && grandparent.isScript()) {
          //                                    NAME/(GETPROP -> ... -> NAME)
          // SCRIPT -> EXPR_RESULT -> ASSIGN ->
          //                                    FUNCTION/CLASS
          Node firstChild = n.getFirstChild();
          Node lastChild = n.getLastChild();
          String nodeName = firstChild.getQualifiedName();

          if (lastChild.isFunction()) {
            if (isTestFunction(nodeName)) {
              if (n.getFirstChild().isName()) {
                exportTestFunctionAsSymbol(nodeName, parent, grandparent);
              } else {
                exportTestFunctionAsProperty(nodeName, parent, n, grandparent);
              }
            }
          } else if (lastChild.isClass()) {
            exportClass(grandparent, lastChild, nodeName, parent);
          }
        }
      } else if (n.isObjectLit()
          && isCallTargetQName(n.getParent(), "goog.testing.testSuite")) {
        for (Node c : n.children()) {
          if (c.isStringKey() && !c.isQuotedString()) {
            c.setQuotedString();
            compiler.reportChangeToEnclosingScope(c);
          } else if (c.isMemberFunctionDef()) {
            rewriteMemberDefInObjLit(c, n);
          }
        }
      }
    }

    private void exportClass(Node scriptNode, Node classNode) {
      String className = NodeUtil.getName(classNode);
      exportClass(scriptNode, classNode, className, classNode);
    }

    private void exportClass(Node scriptNode, Node classNode, String className, Node addAfter) {
      Node classMembers = classNode.getLastChild();
      for (Node maybeMemberFunctionDef : classMembers.children()) {
        if (maybeMemberFunctionDef.isMemberFunctionDef()) {
          String methodName = maybeMemberFunctionDef.getString();
          if (isTestFunction(methodName)) {
            String functionRef = className + ".prototype." + methodName;
            String classRef = className + ".prototype";

            Node exportCallTarget =
                NodeUtil.newQName(
                    compiler, exportPropertyFunction, maybeMemberFunctionDef, methodName);
            Node call = IR.call(exportCallTarget);
            if (exportCallTarget.isName()) {
              call.putBooleanProp(Node.FREE_CALL, true);
            }

            call.addChildToBack(
                NodeUtil.newQName(compiler, classRef, maybeMemberFunctionDef, classRef));
            call.addChildToBack(IR.string(methodName));
            call.addChildToBack(
                NodeUtil.newQName(compiler, functionRef, maybeMemberFunctionDef, functionRef));

            Node expression = IR.exprResult(call);

            scriptNode.addChildAfter(expression, addAfter);
            compiler.reportChangeToEnclosingScope(expression);
            addAfter = expression;
          }
        }
      }
    }

    /** Converts a member function into a quoted string key to avoid property renaming */
    private void rewriteMemberDefInObjLit(Node memberDef, Node objLit) {
      String name = memberDef.getString();
      Node stringKey = IR.stringKey(name, memberDef.getFirstChild().detach());
      objLit.replaceChild(memberDef, stringKey);
      stringKey.setQuotedString();
      stringKey.setJSDocInfo(memberDef.getJSDocInfo());
      compiler.reportChangeToEnclosingScope(objLit);
    }

    // TODO(johnlenz): move test suite declaration into the
    // coding convention class.
    private boolean isCallTargetQName(Node n, String qname) {
      return (n.isCall() && n.getFirstChild().matchesQualifiedName(qname));
    }

    /**
     * Get the node that corresponds to an expression declared with var, let or const.
     * This has the AST structure VAR/LET/CONST -> NAME -> NODE
     * @param node
     */
    private Node getNameDeclaredGrandchild(Node node) {
      if (!NodeUtil.isNameDeclaration(node)) {
        return null;
      }
      return node.getFirstFirstChild();
    }

    /**
     * Whether node corresponds to a function expression declared with var, let
     * or const which is of the form:
     *

     * var/let/const functionName = function() {
     *   // Implementation
     * };
     *

     * This has the AST structure VAR/LET/CONST -> NAME -> FUNCTION
     * @param node
     */
    private boolean isNameDeclaredFunction(Node node) {
      Node grandchild = getNameDeclaredGrandchild(node);
      return grandchild != null && grandchild.isFunction();
    }

    /**
     * Whether node corresponds to a class declared with var, let or const which
     * is of the form:
     *

     * var/let/const className = class {
     *   // Implementation
     * };
     *

     * This has the AST structure VAR/LET/CONST -> NAME -> CLASS
     * @param node
     */
    private boolean isNameDeclaredClass(Node node) {
      Node grandchild = getNameDeclaredGrandchild(node);
      return grandchild != null && grandchild.isClass();
    }
  }

  @Override
  public void process(Node externs, Node root) {
    NodeTraversal.traverse(compiler, root, new ExportTestFunctionsNodes());
  }

  // Adds exportSymbol(testFunctionName, testFunction);
  private void exportTestFunctionAsSymbol(String testFunctionName, Node node,
      Node scriptNode) {

    Node exportCallTarget = NodeUtil.newQName(compiler,
        exportSymbolFunction, node, testFunctionName);
    Node call = IR.call(exportCallTarget);
    if (exportCallTarget.isName()) {
      call.putBooleanProp(Node.FREE_CALL, true);
    }
    call.addChildToBack(IR.string(testFunctionName));
    call.addChildToBack(NodeUtil.newQName(compiler,
        testFunctionName, node, testFunctionName));

    Node expression = IR.exprResult(call);

    scriptNode.addChildAfter(expression, node);
    compiler.reportChangeToEnclosingScope(expression);
  }

  // Adds exportProperty() of the test function name on the prototype object
  private void exportTestFunctionAsProperty(String fullyQualifiedFunctionName,
      Node parent, Node node, Node scriptNode) {

    String testFunctionName =
        NodeUtil.getPrototypePropertyName(node.getFirstChild());
    if (node.getFirstChild().getQualifiedName().startsWith("window.")) {
      testFunctionName = node.getFirstChild().getQualifiedName().substring("window.".length());
    }
    String objectName = fullyQualifiedFunctionName.substring(0,
        fullyQualifiedFunctionName.lastIndexOf('.'));
    String exportCallStr = SimpleFormat.format("%s(%s, '%s', %s);",
        exportPropertyFunction, objectName, testFunctionName,
        fullyQualifiedFunctionName);

    Node exportCall = this.compiler.parseSyntheticCode(exportCallStr)
        .removeChildren();
    exportCall.useSourceInfoFromForTree(scriptNode);

    scriptNode.addChildrenAfter(exportCall, parent);
    compiler.reportChangeToEnclosingScope(exportCall);
  }

  /**
   * Whether a function is recognized as a test function. We follow the JsUnit
   * convention for naming (functions should start with "test"), and we also
   * check if it has no parameters declared.
   *
   * @param functionName The name of the function
   * @return {@code true} if the function is recognized as a test function.
   */
  public static boolean isTestFunction(String functionName) {
    return functionName != null
        && TEST_FUNCTIONS_NAME_PATTERN.matcher(functionName).matches();
  }
}


text:
package com.example.kanjuice.util;

import android.util.Log;

public class Logger {

    private String LOG_TAG;

    private Logger(Class clazz) {
        this.LOG_TAG = clazz.getSimpleName();
    }

    public static Logger loggerFor(Class clazz) {
        return new Logger(clazz);
    }

    public void d(String message) {
        Log.d(LOG_TAG, message);
    }

    public void e(String message) {
        Log.e(LOG_TAG, message);
    }

    public void e(String message, Throwable throwable) {
        Log.e(LOG_TAG, message, throwable);
    }

    public void i(String message) {
        Log.i(LOG_TAG, message);
    }

    public void d(String message, Throwable throwable) {
        Log.d(LOG_TAG, message, throwable);
    }
}


text:
Web design is sometimes thought of as the finishing touches to a web-based project, but in practice, good web design should inform the entire process of development from the beginning.

The 6 phases of web design as defined in the reading are:

1. Information Gathering

2. Planning

3. Design

4. Development

5. Testing and Delivery

6. Maintenance

My personal site will be designed to establish a professional focus for my development career - to provide information about me to clients and potential employers as well as contact and social media info for collaboration with other professionals. Besides basic info and contacts, my site will host projects I've done to serve as an online portfolio. This content will address all 3 groups of anticipated viewers, or my audience (clients, employers, other developers). Here is my first quick sketch of a site map:

![site-map](/week-2/imgs/site-map.JPG)

As primary actions users can take from the home page, contact and portfolio will have priority. All pages branching from the index will be linked in a navigation bar, but these 2 will be specially highlighted with either a prominent link or call-to-action buttons.

User experience development comes from the idea that web pages and applications should be built with users in mind. Just like advertisers market to a target audience, web developers should seek to orient the look and structure of a web experience to best suit the user. This is not just style and aesthetics, although those are important, but also the flow of a page and overall site structure. Some developers are UX experts specifically, but in general it's a concept that should elevate the best practices of all web professionals.

The only frustrations I felt in this assignment were during the sketch for my site map. I wouldn't call it 'tedious', I just froze at first when trying to conceptualize my professional site, but then realized I was overthinking it at this stage.


text:
from .run import cli_run, session_via_cli
from .version import __version__

__all__ = [
    "__version__",
    "cli_run",
    "session_via_cli",
]


text: module Control.Disruptor.Example where


text:
package org.mapfish.print.map.geotools.function;

import org.geotools.filter.FunctionExpressionImpl;
import org.geotools.filter.capability.FunctionNameImpl;
import org.opengis.filter.capability.FunctionName;

import static org.geotools.filter.capability.FunctionNameImpl.parameter;

/**
 * A Function that multiplies the two values.
 *
* @author Jesse on 11/7/2014.
*/
public final class MultiplicationFunction extends FunctionExpressionImpl {

    /**
     * The name of this function.
     */
    public static final FunctionName NAME = new FunctionNameImpl("multiplication",
            parameter("result", Double.class),
            parameter("value1", Double.class),
            parameter("value2", Double.class));

    /**
     * Default constructor.
     */
    public MultiplicationFunction() {
        super(NAME);
    }

    @Override
    public Object evaluate(final Object feature) {
        double value1;
        double value2;

        try { // attempt to get value and perform conversion
            value1 = (getExpression(0).evaluate(feature, Double.class));
        } catch (Exception e) {
            // probably a type error
            throw new IllegalArgumentException(
                    "Filter Function problem for function abs argument #0 - expected type double");
        }
        try { // attempt to get value and perform conversion
            value2 = (getExpression(1).evaluate(feature, Double.class));
        } catch (Exception e) {
            // probably a type error
            throw new IllegalArgumentException(
                    "Filter Function problem for function abs argument #1 - expected type double");
        }

        return value1 * value2;
    }
}


text:
from thinglang.parser.definitions.method_definition import MethodDefinition
from thinglang.parser.definitions.thing_definition import ThingDefinition

def inspects(*args, predicate=None, priority=0):
    """
    Tags a TreeTraversal inspector method
    :param args: AST node types accepted by this inspector, if predicate is not set
    :param predicate: a custom entrance function - overrides args
    :param priority: the order in which this inspector will be called, relative to other inspectors
    """
    if predicate is None:
        def predicate(node):
            return isinstance(node, args) if args else True

    def decorator(func):
        func.predicate = predicate
        func.priority = priority
        return func

    return decorator

class TreeTraversal(object):
    """
    A helper class implementing DFS passes over the AST.
    Automatically keeps track of the current ThingDefinition and MethodDefinition being analyzed
    """

    def __init__(self, ast):
        self.ast = ast
        self.results = []
        self.inspections = sorted((getattr(self, member) for member in dir(self) if
                                   hasattr(getattr(self, member), 'predicate')), key=lambda x: x.priority)

        self.current_thing, self.current_method = None, None

    def run(self):
        self.traverse(self.ast)

    def traverse(self, node):
        self.inspect(node)

        for child in node.children:
            self.traverse(child)

    def inspect(self, node):
        for inspection in self.inspections:
            if inspection.predicate(node):
                inspection(node)

    @inspects(ThingDefinition)
    def update_thing_context(self, node: ThingDefinition):
        self.current_thing = node

    @inspects(MethodDefinition)
    def update_method_context(self, node: MethodDefinition):
        self.current_method = node


text:
id: bad87fee1348bd9aedf08820
title: Convierte una imagen en un enlace
challengeType: 0
videoUrl: 'https://scrimba.com/p/pVMPUv/cRdBnUr'
forumTopicId: 18327
dashedName: turn-an-image-into-a-link
---

# --description--

Puedes convertir elementos en enlaces, anidándolos dentro de un elemento `a`.

Anida tu imagen dentro de un elemento `a`. A continuación, te presentamos un ejemplo:

```html
<a href="#"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="Three kittens running towards the camera."></a>
```

Recuerda usar `#` como propiedad `href` de tu elemento `a` para convertirlo en un enlace muerto.

# --instructions--

Coloca el elemento de imagen existente dentro de un elemento `a` (*anchor*).

Una vez que hayas hecho esto, pasa el cursor sobre tu imagen. El puntero habitual de tu cursor debería convertirse en un puntero de click de enlace. Ahora la foto es un enlace.

# --hints--

El elemento `img` existente debe estar anidado dentro de un elemento `a`.

```js
assert($('a').children('img').length > 0);
```

Tu elemento `a` debe ser un enlace muerto con un atributo `href` establecido como `#`.

```js
assert(new RegExp('#').test($('a').children('img').parent().attr('href')));
```

Cada uno de tus elementos `a` debe tener una etiqueta de cierre.

```js
assert(
  code.match(/<\/a>/g) &&
    code.match(/<a/g) &&
    code.match(/<\/a>/g).length === code.match(/<a/g).length
);
```

# --seed--

## --seed-contents--

```html
<h2>CatPhotoApp</h2>
<main>
  <p>Click here to view more <a href="#">cat photos</a>.</p>

  <img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back.">

  <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p>
  <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p>
</main>
```

# --solutions--

```html
<h2>CatPhotoApp</h2>
<main>
  <p>Click here to view more <a href="#">cat photos</a>.</p>

  <a href="#"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>

  <p>Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.</p>
  <p>Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.</p>
</main>
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>stream-apps-common</artifactId>
		<groupId>org.springframework.cloud.stream.app</groupId>
		<version>3.0.0.BUILD-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>

	<artifactId>stream-apps-test-support</artifactId>

	<dependencies>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-test</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-test-support</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

</project>