text:
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: keir@google.com (Keir Mierle)
//
// A jacobian writer that directly writes to compressed row sparse matrices.

#ifndef CERES_INTERNAL_COMPRESSED_ROW_JACOBIAN_WRITER_H_
#define CERES_INTERNAL_COMPRESSED_ROW_JACOBIAN_WRITER_H_

#include <utility>
#include <vector>

#include "ceres/evaluator.h"
#include "ceres/scratch_evaluate_preparer.h"

namespace ceres {
namespace internal {

class CompressedRowSparseMatrix;
class Program;
class SparseMatrix;

class CompressedRowJacobianWriter {
 public:
  CompressedRowJacobianWriter(Evaluator::Options /* ignored */,
                              Program* program)
    : program_(program) {
  }

  // PopulateJacobianRowAndColumnBlockVectors sets col_blocks and
  // row_blocks for a CompressedRowSparseMatrix, based on the
  // parameter block sizes and residual sizes respectively from the
  // program. This is useful when Solver::Options::use_block_amd =
  // true;
  //
  // This function is static so that it is available to other jacobian
  // writers which use CompressedRowSparseMatrix (or derived types).
  // (Jacobian writers do not fall under any type hierarchy; they only
  // have to provide an interface as specified in program_evaluator.h).
  static void PopulateJacobianRowAndColumnBlockVectors(
      const Program* program,
      CompressedRowSparseMatrix* jacobian);

  // It is necessary to determine the order of the jacobian blocks
  // before copying them into a CompressedRowSparseMatrix (or derived
  // type).  Just because a cost function uses parameter blocks 1
  // after 2 in its arguments does not mean that the block 1 occurs
  // before block 2 in the column layout of the jacobian. Thus,
  // GetOrderedParameterBlocks determines the order by sorting the
  // jacobian blocks by their position in the state vector.
  //
  // This function is static so that it is available to other jacobian
  // writers which use CompressedRowSparseMatrix (or derived types).
  // (Jacobian writers do not fall under any type hierarchy; they only
  // have to provide an interface as specified in
  // program_evaluator.h).
  static void GetOrderedParameterBlocks(
      const Program* program,
      int residual_id,
      std::vector<std::pair<int, int> >* evaluated_jacobian_blocks);

  // JacobianWriter interface.

  // Since the compressed row matrix has different layout than that
  // assumed by the cost functions, use scratch space to store the
  // jacobians temporarily then copy them over to the larger jacobian
  // in the Write() function.
  ScratchEvaluatePreparer* CreateEvaluatePreparers(int num_threads) {
    return ScratchEvaluatePreparer::Create(*program_, num_threads);
  }

  SparseMatrix* CreateJacobian() const;

  void Write(int residual_id,
             int residual_offset,
             double **jacobians,
             SparseMatrix* base_jacobian);

 private:
  Program* program_;
};

}  // namespace internal
}  // namespace ceres

#endif  // CERES_INTERNAL_COMPRESSED_ROW_JACOBIAN_WRITER_H_


text:
package org.kie.server.controller.websocket.common.decoder;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

import org.kie.server.controller.api.model.notification.KieServerControllerNotification;
import org.kie.server.controller.websocket.common.WebSocketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KieServerControllerNotificationDecoder implements Decoder.Text<KieServerControllerNotification> {

    private static final Logger LOGGER = LoggerFactory.getLogger(KieServerControllerNotificationDecoder.class);

    @Override
    public KieServerControllerNotification decode(final String content) throws DecodeException {
        LOGGER.debug("Content received for decoding: {}",
                     content);
        return WebSocketUtils.unmarshal(content,
                                        KieServerControllerNotification.class);
    }

    @Override
    public boolean willDecode(final String content) {
        return content != null;
    }

    @Override
    public void init(final EndpointConfig config) {

    }

    @Override
    public void destroy() {

    }
}

redpajama_set_name: RedPajamaGithub


text:
import { commands, env, TextDocumentShowOptions, Uri, window } from 'vscode';
import type { CreatePullRequestActionContext, OpenPullRequestActionContext } from '../api/gitlens';
import type {
	DiffWithCommandArgs,
	DiffWithPreviousCommandArgs,
	DiffWithWorkingCommandArgs,
	OpenFileAtRevisionCommandArgs,
} from '../commands';
import { GitActions } from '../commands/gitCommands.actions';
import { configuration, FileAnnotationType, ViewShowBranchComparison } from '../configuration';
import { Commands, ContextKeys, CoreCommands, CoreGitCommands } from '../constants';
import { Container } from '../container';
import { setContext } from '../context';
import { GitUri } from '../git/gitUri';
import { GitReference, GitRevision } from '../git/models';
import {
	executeActionCommand,
	executeCommand,
	executeCoreCommand,
	executeCoreGitCommand,
	executeEditorCommand,
} from '../system/command';
import { debug } from '../system/decorators/log';
import { OpenWorkspaceLocation } from '../system/utils';
import { runGitCommandInTerminal } from '../terminal';
import {
	BranchesNode,
	BranchNode,
	BranchTrackingStatusNode,
	canClearNode,
	canEditNode,
	canViewDismissNode,
	CommitFileNode,
	CommitNode,
	CompareBranchNode,
	ContributorNode,
	ContributorsNode,
	FileHistoryNode,
	FileRevisionAsCommitNode,
	FolderNode,
	LineHistoryNode,
	MergeConflictFileNode,
	PageableViewNode,
	PagerNode,
	PullRequestNode,
	RemoteNode,
	RemotesNode,
	RepositoryFolderNode,
	RepositoryNode,
	ResultsFileNode,
	ResultsFilesNode,
	StashFileNode,
	StashNode,
	StatusFileNode,
	TagNode,
	TagsNode,
	ViewNode,
	ViewRefFileNode,
	ViewRefNode,
	WorktreeNode,
	WorktreesNode,
} from './nodes';

interface CompareSelectedInfo {
	ref: string;
	repoPath: string | undefined;
	uri?: Uri;
}

export class ViewCommands {
	constructor(private readonly container: Container) {
		commands.registerCommand('gitlens.views.clearNode', (n: ViewNode) => canClearNode(n) && n.clear(), this);
		commands.registerCommand(
			'gitlens.views.copy',
			async (selection: ViewNode | ViewNode[]) => {
				selection = Array.isArray(selection) ? selection : [selection];
				if (selection.length === 0) return;

				const data = selection
					.map(n => n.toClipboard?.())
					.filter(s => s != null && s.length > 0)
					.join(',');
				await env.clipboard.writeText(data);
			},
			this,
		);
		commands.registerCommand(
			'gitlens.views.dismissNode',
			(n: ViewNode) => canViewDismissNode(n.view) && n.view.dismissNode(n),
			this,
		);
		commands.registerCommand('gitlens.views.editNode', (n: ViewNode) => canEditNode(n) && n.edit(), this);
		commands.registerCommand(
			'gitlens.views.expandNode',
			(n: ViewNode) => n.view.reveal(n, { select: false, focus: false, expand: 3 }),
			this,
		);
		commands.registerCommand('gitlens.views.loadMoreChildren', (n: PagerNode) => n.loadMore(), this);
		commands.registerCommand('gitlens.views.loadAllChildren', (n: PagerNode) => n.loadAll(), this);
		commands.registerCommand(
			'gitlens.views.refreshNode',
			(n: ViewNode, reset?: boolean) => {
				if (reset == null && PageableViewNode.is(n)) {
					n.limit = undefined;
					n.view.resetNodeLastKnownLimit(n);
				}

				return n.view.refreshNode(n, reset == null ? true : reset);
			},
			this,
		);

		commands.registerCommand(
			'gitlens.views.setShowRelativeDateMarkersOn',
			() => this.setShowRelativeDateMarkers(true),
			this,
		);
		commands.registerCommand(
			'gitlens.views.setShowRelativeDateMarkersOff',
			() => this.setShowRelativeDateMarkers(false),
			this,
		);

		commands.registerCommand('gitlens.views.fetch', this.fetch, this);
		commands.registerCommand('gitlens.views.publishBranch', this.publishBranch, this);
		commands.registerCommand('gitlens.views.publishRepository', this.publishRepository, this);
		commands.registerCommand('gitlens.views.pull', this.pull, this);
		commands.registerCommand('gitlens.views.push', this.push, this);
		commands.registerCommand('gitlens.views.pushWithForce', n => this.push(n, true), this);
		commands.registerCommand('gitlens.views.closeRepository', this.closeRepository, this);

		commands.registerCommand('gitlens.views.setAsDefault', this.setAsDefault, this);
		commands.registerCommand('gitlens.views.unsetAsDefault', this.unsetAsDefault, this);

		commands.registerCommand('gitlens.views.openInTerminal', this.openInTerminal, this);
		commands.registerCommand('gitlens.views.star', this.star, this);
		commands.registerCommand('gitlens.views.unstar', this.unstar, this);

		commands.registerCommand('gitlens.views.browseRepoAtRevision', this.browseRepoAtRevision, this);
		commands.registerCommand(
			'gitlens.views.browseRepoAtRevisionInNewWindow',
			n => this.browseRepoAtRevision(n, { openInNewWindow: true }),
			this,
		);
		commands.registerCommand(
			'gitlens.views.browseRepoBeforeRevision',
			n => this.browseRepoAtRevision(n, { before: true }),
			this,
		);
		commands.registerCommand(
			'gitlens.views.browseRepoBeforeRevisionInNewWindow',
			n => this.browseRepoAtRevision(n, { before: true, openInNewWindow: true }),
			this,
		);

		commands.registerCommand('gitlens.views.addAuthors', this.addAuthors, this);
		commands.registerCommand('gitlens.views.addAuthor', this.addAuthors, this);

		commands.registerCommand('gitlens.views.openChanges', this.openChanges, this);
		commands.registerCommand('gitlens.views.openChangesWithWorking', this.openChangesWithWorking, this);
		commands.registerCommand(
			'gitlens.views.openPreviousChangesWithWorking',
			this.openPreviousChangesWithWorking,
			this,
		);
		commands.registerCommand('gitlens.views.openFile', this.openFile, this);
		commands.registerCommand('gitlens.views.openFileRevision', this.openRevision, this);
		commands.registerCommand('gitlens.views.openChangedFiles', this.openFiles, this);
		commands.registerCommand('gitlens.views.openChangedFileDiffs', this.openAllChanges, this);
		commands.registerCommand('gitlens.views.openChangedFileDiffsWithWorking', this.openAllChangesWithWorking, this);
		commands.registerCommand('gitlens.views.openChangedFileRevisions', this.openRevisions, this);
		commands.registerCommand('gitlens.views.applyChanges', this.applyChanges, this);
		commands.registerCommand('gitlens.views.highlightChanges', this.highlightChanges, this);
		commands.registerCommand('gitlens.views.highlightRevisionChanges', this.highlightRevisionChanges, this);
		commands.registerCommand('gitlens.views.restore', this.restore, this);
		commands.registerCommand('gitlens.views.switchToBranch', this.switch, this);
		commands.registerCommand('gitlens.views.switchToAnotherBranch', this.switch, this);
		commands.registerCommand('gitlens.views.switchToCommit', this.switch, this);
		commands.registerCommand('gitlens.views.switchToTag', this.switch, this);
		commands.registerCommand('gitlens.views.addRemote', this.addRemote, this);
		commands.registerCommand('gitlens.views.pruneRemote', this.pruneRemote, this);

		commands.registerCommand('gitlens.views.stageDirectory', this.stageDirectory, this);
		commands.registerCommand('gitlens.views.stageFile', this.stageFile, this);
		commands.registerCommand('gitlens.views.unstageDirectory', this.unstageDirectory, this);
		commands.registerCommand('gitlens.views.unstageFile', this.unstageFile, this);

		commands.registerCommand('gitlens.views.compareAncestryWithWorking', this.compareAncestryWithWorking, this);
		commands.registerCommand('gitlens.views.compareWithHead', this.compareHeadWith, this);
		commands.registerCommand('gitlens.views.compareWithUpstream', this.compareWithUpstream, this);
		commands.registerCommand('gitlens.views.compareWithSelected', this.compareWithSelected, this);
		commands.registerCommand('gitlens.views.selectForCompare', this.selectForCompare, this);
		commands.registerCommand('gitlens.views.compareFileWithSelected', this.compareFileWithSelected, this);
		commands.registerCommand('gitlens.views.selectFileForCompare', this.selectFileForCompare, this);
		commands.registerCommand('gitlens.views.compareWithWorking', this.compareWorkingWith, this);

		commands.registerCommand(
			'gitlens.views.setBranchComparisonToWorking',
			n => this.setBranchComparison(n, ViewShowBranchComparison.Working),
			this,
		);
		commands.registerCommand(
			'gitlens.views.setBranchComparisonToBranch',
			n => this.setBranchComparison(n, ViewShowBranchComparison.Branch),
			this,
		);

		commands.registerCommand('gitlens.views.cherryPick', this.cherryPick, this);
		commands.registerCommand('gitlens.views.createBranch', this.createBranch, this);
		commands.registerCommand('gitlens.views.deleteBranch', this.deleteBranch, this);
		commands.registerCommand('gitlens.views.renameBranch', this.renameBranch, this);
		commands.registerCommand('gitlens.views.deleteStash', this.deleteStash, this);
		commands.registerCommand('gitlens.views.createTag', this.createTag, this);
		commands.registerCommand('gitlens.views.deleteTag', this.deleteTag, this);

		commands.registerCommand('gitlens.views.mergeBranchInto', this.merge, this);
		commands.registerCommand('gitlens.views.pushToCommit', this.pushToCommit, this);

		commands.registerCommand('gitlens.views.rebaseOntoBranch', this.rebase, this);
		commands.registerCommand('gitlens.views.rebaseOntoUpstream', this.rebaseToRemote, this);
		commands.registerCommand('gitlens.views.rebaseOntoCommit', this.rebase, this);

		commands.registerCommand('gitlens.views.resetCommit', this.resetCommit, this);
		commands.registerCommand('gitlens.views.resetToCommit', this.resetToCommit, this);
		commands.registerCommand('gitlens.views.revert', this.revert, this);
		commands.registerCommand('gitlens.views.undoCommit', this.undoCommit, this);

		commands.registerCommand('gitlens.views.terminalRemoveRemote', this.terminalRemoveRemote, this);

		commands.registerCommand('gitlens.views.createPullRequest', this.createPullRequest, this);
		commands.registerCommand('gitlens.views.openPullRequest', this.openPullRequest, this);

		commands.registerCommand('gitlens.views.createWorktree', this.createWorktree, this);
		commands.registerCommand('gitlens.views.deleteWorktree', this.deleteWorktree, this);
		commands.registerCommand('gitlens.views.openWorktree', this.openWorktree, this);
		commands.registerCommand('gitlens.views.revealWorktreeInExplorer', this.revealWorktreeInExplorer, this);
		commands.registerCommand(
			'gitlens.views.openWorktreeInNewWindow',
			n => this.openWorktree(n, { location: OpenWorkspaceLocation.NewWindow }),
			this,
		);
	}

	@debug()
	private addAuthors(node?: ContributorNode | ContributorsNode) {
		if (node != null && !(node instanceof ContributorNode) && !(node instanceof ContributorsNode)) {
			return Promise.resolve();
		}

		return GitActions.Contributor.addAuthors(
			node?.uri.repoPath,
			node instanceof ContributorNode ? node.contributor : undefined,
		);
	}

	@debug()
	private addRemote(node?: RemotesNode) {
		return GitActions.Remote.add(node?.repoPath);
	}

	@debug()
	private applyChanges(node: ViewRefFileNode) {
		if (!(node instanceof ViewRefFileNode)) return Promise.resolve();

		if (node instanceof ResultsFileNode) {
			return GitActions.Commit.applyChanges(
				node.file,
				GitReference.create(node.ref1, node.repoPath),
				GitReference.create(node.ref2, node.repoPath),
			);
		}

		if (node.ref == null || node.ref.ref === 'HEAD') return Promise.resolve();

		return GitActions.Commit.applyChanges(node.file, node.ref);
	}

	@debug()
	private browseRepoAtRevision(node: ViewRefNode, options?: { before?: boolean; openInNewWindow?: boolean }) {
		if (!(node instanceof ViewRefNode)) return Promise.resolve();

		return GitActions.browseAtRevision(node.uri, {
			before: options?.before,
			openInNewWindow: options?.openInNewWindow,
		});
	}

	@debug()
	private cherryPick(node: CommitNode) {
		if (!(node instanceof CommitNode)) return Promise.resolve();

		return GitActions.cherryPick(node.repoPath, node.ref);
	}

	@debug()
	private closeRepository(node: RepositoryNode | RepositoryFolderNode) {
		if (!(node instanceof RepositoryNode) && !(node instanceof RepositoryFolderNode)) return;

		node.repo.closed = true;
	}

	@debug()
	private async createBranch(node?: ViewRefNode | BranchesNode | BranchTrackingStatusNode) {
		let from =
			node instanceof ViewRefNode
				? node?.ref
				: node instanceof BranchTrackingStatusNode
				? node.branch
				: undefined;
		if (from == null) {
			const branch = await this.container.git.getBranch(
				node?.repoPath ?? this.container.git.getBestRepository()?.uri,
			);
			from = branch;
		}
		return GitActions.Branch.create(node?.repoPath, from);
	}

	@debug()
	private async createWorktree(node?: BranchNode | WorktreesNode) {
		if (node instanceof WorktreesNode) {
			node = undefined;
		}
		if (node != null && !(node instanceof BranchNode)) return undefined;

		return GitActions.Worktree.create(node?.repoPath, undefined, node?.ref);
	}

	@debug()
	private openWorktree(node: WorktreeNode, options?: { location?: OpenWorkspaceLocation }) {
		if (!(node instanceof WorktreeNode)) return undefined;

		return GitActions.Worktree.open(node.worktree, options);
	}

	@debug()
	private revealWorktreeInExplorer(node: WorktreeNode) {
		if (!(node instanceof WorktreeNode)) return undefined;

		return GitActions.Worktree.revealInFileExplorer(node.worktree);
	}

	@debug()
	private async deleteWorktree(node: WorktreeNode) {
		if (!(node instanceof WorktreeNode)) return undefined;

		return GitActions.Worktree.remove(node.repoPath, node.worktree.uri);
	}

	@debug()
	private async createPullRequest(node: BranchNode | BranchTrackingStatusNode) {
		if (!(node instanceof BranchNode) && !(node instanceof BranchTrackingStatusNode)) {
			return Promise.resolve();
		}

		const remote = await node.branch.getRemote();

		return executeActionCommand<CreatePullRequestActionContext>('createPullRequest', {
			repoPath: node.repoPath,
			remote:
				remote != null
					? {
							name: remote.name,
							provider:
								remote.provider != null
									? {
											id: remote.provider.id,
											name: remote.provider.name,
											domain: remote.provider.domain,
									  }
									: undefined,
							url: remote.url,
					  }
					: undefined,
			branch: {
				name: node.branch.name,
				upstream: node.branch.upstream?.name,
				isRemote: node.branch.remote,
			},
		});
	}

	@debug()
	private async createTag(node?: ViewRefNode | TagsNode | BranchTrackingStatusNode) {
		let from =
			node instanceof ViewRefNode
				? node?.ref
				: node instanceof BranchTrackingStatusNode
				? node.branch
				: undefined;
		if (from == null) {
			const branch = await this.container.git.getBranch(
				node?.repoPath ?? this.container.git.getBestRepository()?.uri,
			);
			from = branch;
		}
		return GitActions.Tag.create(node?.repoPath, from);
	}

	@debug()
	private deleteBranch(node: BranchNode) {
		if (!(node instanceof BranchNode)) return Promise.resolve();

		return GitActions.Branch.remove(node.repoPath, node.branch);
	}

	@debug()
	private deleteStash(node: StashNode) {
		if (!(node instanceof StashNode)) return Promise.resolve();

		return GitActions.Stash.drop(node.repoPath, node.commit);
	}

	@debug()
	private deleteTag(node: TagNode) {
		if (!(node instanceof TagNode)) return Promise.resolve();

		return GitActions.Tag.remove(node.repoPath, node.tag);
	}

	@debug()
	private fetch(node: RemoteNode | RepositoryNode | RepositoryFolderNode | BranchNode | BranchTrackingStatusNode) {
		if (node instanceof RepositoryNode || node instanceof RepositoryFolderNode) return GitActions.fetch(node.repo);
		if (node instanceof RemoteNode) return GitActions.Remote.fetch(node.remote.repoPath, node.remote.name);
		if (node instanceof BranchNode || node instanceof BranchTrackingStatusNode) {
			return GitActions.fetch(node.repoPath, node.root ? undefined : node.branch);
		}

		return Promise.resolve();
	}

	@debug()
	private async highlightChanges(node: CommitFileNode | StashFileNode | FileRevisionAsCommitNode | ResultsFileNode) {
		if (
			!(node instanceof CommitFileNode) &&
			!(node instanceof StashFileNode) &&
			!(node instanceof FileRevisionAsCommitNode) &&
			!(node instanceof ResultsFileNode)
		) {
			return;
		}

		void (await this.openFile(node, { preserveFocus: true, preview: true }));
		void (await this.container.fileAnnotations.toggle(
			window.activeTextEditor,
			FileAnnotationType.Changes,
			{ sha: node.ref.ref },
			true,
		));
	}

	@debug()
	private async highlightRevisionChanges(
		node: CommitFileNode | StashFileNode | FileRevisionAsCommitNode | ResultsFileNode,
	) {
		if (
			!(node instanceof CommitFileNode) &&
			!(node instanceof StashFileNode) &&
			!(node instanceof FileRevisionAsCommitNode) &&
			!(node instanceof ResultsFileNode)
		) {
			return;
		}

		void (await this.openFile(node, { preserveFocus: true, preview: true }));
		void (await this.container.fileAnnotations.toggle(
			window.activeTextEditor,
			FileAnnotationType.Changes,
			{ sha: node.ref.ref, only: true },
			true,
		));
	}

	@debug()
	private merge(node: BranchNode | TagNode) {
		if (!(node instanceof BranchNode) && !(node instanceof TagNode)) return Promise.resolve();

		return GitActions.merge(node.repoPath, node instanceof BranchNode ? node.branch : node.tag);
	}

	@debug()
	private pushToCommit(node: CommitNode | FileRevisionAsCommitNode) {
		if (!(node instanceof CommitNode) && !(node instanceof FileRevisionAsCommitNode)) return Promise.resolve();

		return GitActions.push(node.repoPath, false, node.commit);
	}

	@debug()
	private openPullRequest(node: PullRequestNode) {
		if (!(node instanceof PullRequestNode)) return Promise.resolve();

		return executeActionCommand<OpenPullRequestActionContext>('openPullRequest', {
			repoPath: node.uri.repoPath!,
			provider: {
				id: node.pullRequest.provider.id,
				name: node.pullRequest.provider.name,
				domain: node.pullRequest.provider.domain,
			},
			pullRequest: {
				id: node.pullRequest.id,
				url: node.pullRequest.url,
			},
		});
	}

	@debug()
	private openInTerminal(node: RepositoryNode | RepositoryFolderNode) {
		if (!(node instanceof RepositoryNode) && !(node instanceof RepositoryFolderNode)) return Promise.resolve();

		return executeCoreCommand(CoreCommands.OpenInTerminal, Uri.file(node.repo.path));
	}

	@debug()
	private async pruneRemote(node: RemoteNode) {
		if (!(node instanceof RemoteNode)) return Promise.resolve();

		return GitActions.Remote.prune(node.repo, node.remote.name);
	}

	@debug()
	private publishBranch(node: BranchNode | BranchTrackingStatusNode) {
		if (node instanceof BranchNode || node instanceof BranchTrackingStatusNode) {
			return GitActions.push(node.repoPath, undefined, node.branch);
		}
		return Promise.resolve();
	}

	@debug()
	private publishRepository(node: BranchNode | BranchTrackingStatusNode) {
		if (node instanceof BranchNode || node instanceof BranchTrackingStatusNode) {
			return executeCoreGitCommand(CoreGitCommands.Publish, Uri.file(node.repoPath));
		}
		return Promise.resolve();
	}

	@debug()
	private pull(node: RepositoryNode | RepositoryFolderNode | BranchNode | BranchTrackingStatusNode) {
		if (node instanceof RepositoryNode || node instanceof RepositoryFolderNode) return GitActions.pull(node.repo);
		if (node instanceof BranchNode || node instanceof BranchTrackingStatusNode) {
			return GitActions.pull(node.repoPath, node.root ? undefined : node.branch);
		}

		return Promise.resolve();
	}

	@debug()
	private push(
		node:
			| RepositoryNode
			| RepositoryFolderNode
			| BranchNode
			| BranchTrackingStatusNode
			| CommitNode
			| FileRevisionAsCommitNode,
		force?: boolean,
	) {
		if (node instanceof RepositoryNode || node instanceof RepositoryFolderNode) {
			return GitActions.push(node.repo, force);
		}

		if (node instanceof BranchNode || node instanceof BranchTrackingStatusNode) {
			return GitActions.push(node.repoPath, undefined, node.root ? undefined : node.branch);
		}

		if (node instanceof CommitNode || node instanceof FileRevisionAsCommitNode) {
			if (node.isTip) {
				return GitActions.push(node.repoPath, force);
			}

			return this.pushToCommit(node);
		}

		return Promise.resolve();
	}

	@debug()
	private rebase(node: BranchNode | CommitNode | FileRevisionAsCommitNode | TagNode) {
		if (
			!(node instanceof BranchNode) &&
			!(node instanceof CommitNode) &&
			!(node instanceof FileRevisionAsCommitNode) &&
			!(node instanceof TagNode)
		) {
			return Promise.resolve();
		}

		return GitActions.rebase(node.repoPath, node.ref);
	}

	@debug()
	private rebaseToRemote(node: BranchNode | BranchTrackingStatusNode) {
		if (!(node instanceof BranchNode) && !(node instanceof BranchTrackingStatusNode)) return Promise.resolve();

		const upstream = node instanceof BranchNode ? node.branch.upstream?.name : node.status.upstream;
		if (upstream == null) return Promise.resolve();

		return GitActions.rebase(
			node.repoPath,
			GitReference.create(upstream, node.repoPath, {
				refType: 'branch',
				name: upstream,
				remote: true,
			}),
		);
	}

	@debug()
	private renameBranch(node: BranchNode) {
		if (!(node instanceof BranchNode)) return Promise.resolve();

		return GitActions.Branch.rename(node.repoPath, node.branch);
	}

	@debug()
	private resetCommit(node: CommitNode | FileRevisionAsCommitNode) {
		if (!(node instanceof CommitNode) && !(node instanceof FileRevisionAsCommitNode)) return Promise.resolve();

		return GitActions.reset(
			node.repoPath,
			GitReference.create(`${node.ref.ref}^`, node.ref.repoPath, {
				refType: 'revision',
				name: `${node.ref.name}^`,
				message: node.ref.message,
			}),
		);
	}

	@debug()
	private resetToCommit(node: CommitNode | FileRevisionAsCommitNode) {
		if (!(node instanceof CommitNode) && !(node instanceof FileRevisionAsCommitNode)) return Promise.resolve();

		return GitActions.reset(node.repoPath, node.ref);
	}

	@debug()
	private restore(node: ViewRefFileNode) {
		if (!(node instanceof ViewRefFileNode)) return Promise.resolve();

		return GitActions.Commit.restoreFile(node.file, node.ref);
	}

	@debug()
	private revert(node: CommitNode | FileRevisionAsCommitNode) {
		if (!(node instanceof CommitNode) && !(node instanceof FileRevisionAsCommitNode)) return Promise.resolve();

		return GitActions.revert(node.repoPath, node.ref);
	}

	@debug()
	private setAsDefault(node: RemoteNode) {
		if (!(node instanceof RemoteNode)) return Promise.resolve();

		return node.setAsDefault();
	}

	@debug()
	private setBranchComparison(node: ViewNode, comparisonType: Exclude<ViewShowBranchComparison, false>) {
		if (!(node instanceof CompareBranchNode)) return undefined;

		return node.setComparisonType(comparisonType);
	}

	@debug()
	private setShowRelativeDateMarkers(enabled: boolean) {
		return configuration.updateEffective('views.showRelativeDateMarkers', enabled);
	}

	@debug()
	private async stageFile(node: CommitFileNode | FileRevisionAsCommitNode | StatusFileNode) {
		if (
			!(node instanceof CommitFileNode) &&
			!(node instanceof FileRevisionAsCommitNode) &&
			!(node instanceof StatusFileNode)
		) {
			return;
		}

		void (await this.container.git.stageFile(node.repoPath, node.file.path));
		void node.triggerChange();
	}

	@debug()
	private async stageDirectory(node: FolderNode) {
		if (!(node instanceof FolderNode) || !node.relativePath) return;

		void (await this.container.git.stageDirectory(node.repoPath, node.relativePath));
		void node.triggerChange();
	}

	@debug()
	private star(node: BranchNode | RepositoryNode | RepositoryFolderNode) {
		if (
			!(node instanceof BranchNode) &&
			!(node instanceof RepositoryNode) &&
			!(node instanceof RepositoryFolderNode)
		) {
			return Promise.resolve();
		}

		return node.star();
	}

	@debug()
	private switch(node?: ViewRefNode | BranchesNode) {
		if (node == null) {
			return GitActions.switchTo(this.container.git.highlander);
		}

		if (!(node instanceof ViewRefNode) && !(node instanceof BranchesNode)) return Promise.resolve();

		return GitActions.switchTo(
			node.repoPath,
			node instanceof BranchesNode || (node instanceof BranchNode && node.branch.current) ? undefined : node.ref,
		);
	}

	@debug()
	private async undoCommit(node: CommitNode | FileRevisionAsCommitNode) {
		if (!(node instanceof CommitNode) && !(node instanceof FileRevisionAsCommitNode)) return;

		const repo = await Container.instance.git.getOrOpenScmRepository(node.repoPath);
		const commit = await repo?.getCommit('HEAD');

		if (commit?.hash !== node.ref.ref) {
			void window.showWarningMessage(
				`Commit ${GitReference.toString(node.ref, {
					capitalize: true,
					icon: false,
				})} cannot be undone, because it is no longer the most recent commit.`,
			);

			return;
		}

		await executeCoreGitCommand(CoreGitCommands.UndoCommit, node.repoPath);
	}

	@debug()
	private unsetAsDefault(node: RemoteNode) {
		if (!(node instanceof RemoteNode)) return Promise.resolve();

		return node.setAsDefault(false);
	}

	@debug()
	private async unstageFile(node: CommitFileNode | FileRevisionAsCommitNode | StatusFileNode) {
		if (
			!(node instanceof CommitFileNode) &&
			!(node instanceof FileRevisionAsCommitNode) &&
			!(node instanceof StatusFileNode)
		) {
			return;
		}

		void (await this.container.git.unStageFile(node.repoPath, node.file.path));
		void node.triggerChange();
	}

	@debug()
	private async unstageDirectory(node: FolderNode) {
		if (!(node instanceof FolderNode) || !node.relativePath) return;

		void (await this.container.git.unStageDirectory(node.repoPath, node.relativePath));
		void node.triggerChange();
	}

	@debug()
	private unstar(node: BranchNode | RepositoryNode | RepositoryFolderNode) {
		if (
			!(node instanceof BranchNode) &&
			!(node instanceof RepositoryNode) &&
			!(node instanceof RepositoryFolderNode)
		) {
			return Promise.resolve();
		}

		return node.unstar();
	}

	@debug()
	private compareHeadWith(node: ViewRefNode) {
		if (!(node instanceof ViewRefNode)) return Promise.resolve();

		return this.container.searchAndCompareView.compare(node.repoPath, 'HEAD', node.ref);
	}

	@debug()
	private compareWithUpstream(node: BranchNode) {
		if (!(node instanceof BranchNode)) return Promise.resolve();
		if (node.branch.upstream == null) return Promise.resolve();

		return this.container.searchAndCompareView.compare(node.repoPath, node.ref, node.branch.upstream.name);
	}

	@debug()
	private compareWorkingWith(node: ViewRefNode) {
		if (!(node instanceof ViewRefNode)) return Promise.resolve();

		return this.container.searchAndCompareView.compare(node.repoPath, '', node.ref);
	}

	@debug()
	private async compareAncestryWithWorking(node: BranchNode) {
		if (!(node instanceof BranchNode)) return undefined;

		const branch = await this.container.git.getBranch(node.repoPath);
		if (branch == null) return undefined;

		const commonAncestor = await this.container.git.getMergeBase(node.repoPath, branch.ref, node.ref.ref);
		if (commonAncestor == null) return undefined;

		return this.container.searchAndCompareView.compare(
			node.repoPath,
			{ ref: commonAncestor, label: `ancestry with ${node.ref.ref} (${GitRevision.shorten(commonAncestor)})` },
			'',
		);
	}

	@debug()
	private compareWithSelected(node: ViewRefNode) {
		if (!(node instanceof ViewRefNode)) return;

		this.container.searchAndCompareView.compareWithSelected(node.repoPath, node.ref);
	}

	@debug()
	private selectForCompare(node: ViewRefNode) {
		if (!(node instanceof ViewRefNode)) return;

		this.container.searchAndCompareView.selectForCompare(node.repoPath, node.ref);
	}

	@debug()
	private compareFileWithSelected(node: ViewRefFileNode) {
		if (this._selectedFile == null || !(node instanceof ViewRefFileNode) || node.ref == null) {
			return Promise.resolve();
		}

		if (this._selectedFile.repoPath !== node.repoPath) {
			this.selectFileForCompare(node);
			return Promise.resolve();
		}

		const selected = this._selectedFile;

		this._selectedFile = undefined;
		void setContext(ContextKeys.ViewsCanCompareFile, false);

		return executeCommand<DiffWithCommandArgs>(Commands.DiffWith, {
			repoPath: selected.repoPath,
			lhs: {
				sha: selected.ref,
				uri: selected.uri!,
			},
			rhs: {
				sha: node.ref.ref,
				uri: node.uri,
			},
		});
	}

	private _selectedFile: CompareSelectedInfo | undefined;

	@debug()
	private selectFileForCompare(node: ViewRefFileNode) {
		if (!(node instanceof ViewRefFileNode) || node.ref == null) return;

		this._selectedFile = {
			ref: node.ref.ref,
			repoPath: node.repoPath,
			uri: node.uri,
		};
		void setContext(ContextKeys.ViewsCanCompareFile, true);
	}

	@debug()
	private async openAllChanges(node: CommitNode | StashNode | ResultsFilesNode, options?: TextDocumentShowOptions) {
		if (!(node instanceof CommitNode) && !(node instanceof StashNode) && !(node instanceof ResultsFilesNode)) {
			return undefined;
		}

		if (node instanceof ResultsFilesNode) {
			const { files: diff } = await node.getFilesQueryResults();
			if (diff == null || diff.length === 0) return undefined;

			return GitActions.Commit.openAllChanges(
				diff,
				{
					repoPath: node.repoPath,
					ref1: node.ref1,
					ref2: node.ref2,
				},
				options,
			);
		}

		return GitActions.Commit.openAllChanges(node.commit, options);
	}

	@debug()
	private openChanges(node: ViewRefFileNode | MergeConflictFileNode | StatusFileNode) {
		if (
			!(node instanceof ViewRefFileNode) &&
			!(node instanceof MergeConflictFileNode) &&
			!(node instanceof StatusFileNode)
		) {
			return;
		}

		if (node instanceof MergeConflictFileNode) {
			void executeCommand<DiffWithCommandArgs>(Commands.DiffWith, {
				lhs: {
					sha: node.status.HEAD.ref,
					uri: GitUri.fromFile(node.file, node.repoPath, undefined, true),
				},
				rhs: {
					sha: 'HEAD',
					uri: GitUri.fromFile(node.file, node.repoPath),
				},
				repoPath: node.repoPath,
				line: 0,
				showOptions: {
					preserveFocus: false,
					preview: false,
				},
			});

			return;
		}

		const command = node.getCommand();
		if (command?.arguments == null) return;

		switch (command.command) {
			case Commands.DiffWith: {
				const [args] = command.arguments as [DiffWithCommandArgs];
				args.showOptions!.preview = false;
				void executeCommand<DiffWithCommandArgs>(command.command, args);
				break;
			}
			case Commands.DiffWithPrevious: {
				const [, args] = command.arguments as [Uri, DiffWithPreviousCommandArgs];
				args.showOptions!.preview = false;
				void executeEditorCommand<DiffWithPreviousCommandArgs>(command.command, undefined, args);
				break;
			}
			default:
				throw new Error(`Unexpected command: ${command.command}`);
		}

		// TODO@eamodio Revisit this
		// return GitActions.Commit.openChanges(node.file, node instanceof ViewRefFileNode ? node.ref : node.commit, {
		// 	preserveFocus: true,
		// 	preview: false,
		// });
	}

	@debug()
	private async openAllChangesWithWorking(
		node: CommitNode | StashNode | ResultsFilesNode,
		options?: TextDocumentShowOptions,
	) {
		if (!(node instanceof CommitNode) && !(node instanceof StashNode) && !(node instanceof ResultsFilesNode)) {
			return undefined;
		}

		if (node instanceof ResultsFilesNode) {
			const { files: diff } = await node.getFilesQueryResults();
			if (diff == null || diff.length === 0) return undefined;

			return GitActions.Commit.openAllChangesWithWorking(
				diff,
				{
					repoPath: node.repoPath,
					ref: node.ref1 || node.ref2,
				},
				options,
			);
		}

		return GitActions.Commit.openAllChangesWithWorking(node.commit, options);

		// options = { preserveFocus: false, preview: false, ...options };

		// let repoPath: string;
		// let files;
		// let ref: string;

		// if (node instanceof ResultsFilesNode) {
		// 	const { diff } = await node.getFilesQueryResults();
		// 	if (diff == null || diff.length === 0) return;

		// 	repoPath = node.repoPath;
		// 	files = diff;
		// 	ref = node.ref1 || node.ref2;
		// } else {
		// 	repoPath = node.commit.repoPath;
		// 	files = node.commit.files;
		// 	ref = node.commit.sha;
		// }

		// if (files.length > 20) {
		// 	const result = await window.showWarningMessage(
		// 		`Are your sure you want to open all ${files.length} files?`,
		// 		{ title: 'Yes' },
		// 		{ title: 'No', isCloseAffordance: true },
		// 	);
		// 	if (result == null || result.title === 'No') return;
		// }

		// for (const file of files) {
		// 	if (file.status === 'A' || file.status === 'D') continue;

		// 	const args: DiffWithWorkingCommandArgs = {
		// 		showOptions: options,
		// 	};

		// 	const uri = GitUri.fromFile(file, repoPath, ref);
		// 	await executeCommand(Commands.DiffWithWorking, uri, args);
		// }
	}

	@debug()
	private async openChangesWithWorking(node: ViewRefFileNode | MergeConflictFileNode | StatusFileNode) {
		if (
			!(node instanceof ViewRefFileNode) &&
			!(node instanceof MergeConflictFileNode) &&
			!(node instanceof StatusFileNode)
		) {
			return Promise.resolve();
		}

		if (node instanceof StatusFileNode) {
			return executeEditorCommand<DiffWithWorkingCommandArgs>(Commands.DiffWithWorking, undefined, {
				uri: node.uri,
				showOptions: {
					preserveFocus: true,
					preview: true,
				},
			});
		} else if (node instanceof MergeConflictFileNode) {
			return executeEditorCommand<DiffWithWorkingCommandArgs>(Commands.DiffWithWorking, undefined, {
				uri: node.baseUri,
				showOptions: {
					preserveFocus: true,
					preview: true,
				},
			});
		} else if (node instanceof FileRevisionAsCommitNode && node.commit.file?.hasConflicts) {
			const baseUri = await node.getConflictBaseUri();
			if (baseUri != null) {
				return executeEditorCommand<DiffWithWorkingCommandArgs>(Commands.DiffWithWorking, undefined, {
					uri: baseUri,
					showOptions: {
						preserveFocus: true,
						preview: true,
					},
				});
			}
		}

		return GitActions.Commit.openChangesWithWorking(node.file, { repoPath: node.repoPath, ref: node.ref.ref });
	}

	@debug()
	private async openPreviousChangesWithWorking(node: ViewRefFileNode) {
		if (!(node instanceof ViewRefFileNode)) return Promise.resolve();

		return GitActions.Commit.openChangesWithWorking(node.file, {
			repoPath: node.repoPath,
			ref: `${node.ref.ref}^`,
		});
	}

	@debug()
	private openFile(
		node: ViewRefFileNode | MergeConflictFileNode | StatusFileNode | FileHistoryNode | LineHistoryNode,
		options?: TextDocumentShowOptions,
	) {
		if (
			!(node instanceof ViewRefFileNode) &&
			!(node instanceof MergeConflictFileNode) &&
			!(node instanceof StatusFileNode) &&
			!(node instanceof FileHistoryNode) &&
			!(node instanceof LineHistoryNode)
		) {
			return Promise.resolve();
		}

		return GitActions.Commit.openFile(node.uri, {
			preserveFocus: true,
			preview: false,
			...options,
		});
	}

	@debug()
	private async openFiles(node: CommitNode | StashNode | ResultsFilesNode) {
		if (!(node instanceof CommitNode) && !(node instanceof StashNode) && !(node instanceof ResultsFilesNode)) {
			return undefined;
		}

		if (node instanceof ResultsFilesNode) {
			const { files: diff } = await node.getFilesQueryResults();
			if (diff == null || diff.length === 0) return undefined;

			return GitActions.Commit.openFiles(diff, node.repoPath, node.ref1 || node.ref2);
		}

		return GitActions.Commit.openFiles(node.commit);
	}

	@debug()
	private async openRevision(
		node:
			| CommitFileNode
			| FileRevisionAsCommitNode
			| ResultsFileNode
			| StashFileNode
			| MergeConflictFileNode
			| StatusFileNode,
		options?: OpenFileAtRevisionCommandArgs,
	) {
		if (
			!(node instanceof CommitFileNode) &&
			!(node instanceof FileRevisionAsCommitNode) &&
			!(node instanceof ResultsFileNode) &&
			!(node instanceof StashFileNode) &&
			!(node instanceof MergeConflictFileNode) &&
			!(node instanceof StatusFileNode)
		) {
			return Promise.resolve();
		}

		options = { showOptions: { preserveFocus: true, preview: false }, ...options };

		let uri = options.revisionUri;
		if (uri == null) {
			if (node instanceof ResultsFileNode || node instanceof MergeConflictFileNode) {
				uri = Container.instance.git.getRevisionUri(node.uri);
			} else {
				uri =
					node.commit.file?.status === 'D'
						? Container.instance.git.getRevisionUri(
								(await node.commit.getPreviousSha()) ?? GitRevision.deletedOrMissing,
								node.commit.file.path,
								node.commit.repoPath,
						  )
						: Container.instance.git.getRevisionUri(node.uri);
			}
		}

		return GitActions.Commit.openFileAtRevision(
			uri,
			options.showOptions ?? { preserveFocus: true, preview: false },
		);
	}

	@debug()
	private async openRevisions(node: CommitNode | StashNode | ResultsFilesNode, _options?: TextDocumentShowOptions) {
		if (!(node instanceof CommitNode) && !(node instanceof StashNode) && !(node instanceof ResultsFilesNode)) {
			return undefined;
		}

		if (node instanceof ResultsFilesNode) {
			const { files: diff } = await node.getFilesQueryResults();
			if (diff == null || diff.length === 0) return undefined;

			return GitActions.Commit.openFilesAtRevision(diff, node.repoPath, node.ref1, node.ref2);
		}

		return GitActions.Commit.openFilesAtRevision(node.commit);
	}

	private terminalRemoveRemote(node: RemoteNode) {
		if (!(node instanceof RemoteNode)) return;

		runGitCommandInTerminal('remote', `remove ${node.remote.name}`, node.remote.repoPath);
	}
}


text:
Call function with external stack
=================================

Overview
--------

A given function can be executed with a user allocated stack space which is independent of current task stack, this mechanism can be used to save stack space wasted by tasks which call a common function with intensive stack usage such as `printf`. The given function can be called inside the shared stack space which is a callback function deferred by calling :cpp:func:`esp_execute_shared_stack_function`, passing that function as parameter.

Usage
-----

:cpp:func:`esp_execute_shared_stack_function` takes four arguments:

- a mutex object allocated by the caller, which is used to protect if the same function shares its allocated stack
- a pointer to the top of stack used for that fuction
- the size of stack in bytes
- a pointer to the shared stack function

The user defined function will be deferred as a callback and can be called using the user allocated space without taking space from current task stack.

The usage may look like the code below:

.. code-block:: c

    void external_stack_function(void)
    {
        printf("Executing this printf from external stack! \n");
    }

    //Let's suppose we want to call printf using a separated stack space
    //allowing the app to reduce its stack size.
    void app_main()
    {
        //Allocate a stack buffer, from heap or as a static form:
        portSTACK_TYPE *shared_stack = malloc(8192 * sizeof(portSTACK_TYPE));
        assert(shared_stack != NULL);

        //Allocate a mutex to protect its usage:
        SemaphoreHandle_t printf_lock = xSemaphoreCreateMutex();
        assert(printf_lock != NULL);

        //Call the desired function using the macro helper:
        esp_execute_shared_stack_function(printf_lock,
                                        shared_stack,
                                        8192,
                                        external_stack_function);

        vSemaphoreDelete(printf_lock);
        free(shared_stack);
    }

.. _esp-call-with-stack-basic_usage:

API Reference
-------------

.. include-build-file:: inc/esp_expression_with_stack.inc


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use backend\models\EstadoSolucionReclamoSugerencia;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\SolucionReclamoSugerenciaSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Soluciones a los Reclamos y Sugerencias';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

<?= Html::a('Ver Reclamos-Sugerencias', ['/reclamo-sugerencia/index'], ['class' => 'btn btn-primary']) ?>
    <?= Html::a('Ver Solicitudes Derivadas', ['/derivacion-reclamo-sugerencia/index'], ['class' => 'btn btn-primary']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'REC_NUMERO',
            'SRS_ID',
            'USU_RUT',
            [
              'attribute'=>'ESR_ID',
              'value'=>'eSR.ESR_ESTADO'
            ],
            'SRS_VISTO_BUENO',
            'SRS_COMENTARIO',
            'SRS_ANTECEDENTES',
            // 'SRS_FECHA_RESPUESTA',
            // 'SRS_FECHA_ENVIO',
            // 'SRS_RESULTADOS',

            ['class' => 'yii\grid\SolucionReclamoSugerenciaActionColumn'],
        ],
    ]); ?>


text:
[![Code Climate](https://codeclimate.com/github/godmodelabs/segony-kernel/badges/gpa.svg)](https://codeclimate.com/github/godmodelabs/segony-kernel) [![Test Coverage](https://codeclimate.com/github/godmodelabs/segony-kernel/badges/coverage.svg)](https://codeclimate.com/github/godmodelabs/segony-kernel) [![Build Status](https://travis-ci.org/godmodelabs/segony-kernel.svg?branch=master)](https://travis-ci.org/godmodelabs/segony-kernel)

> Segony is a simple framework used for sites with recurring content segments. You can configure every segment separately and combine them with different views.
The framework consists of "sites", "layouts" and "segments". These can be configured separately. This is how it works:

- Kernel `initialize`
    - Register necessary services
    - Initialize configuration
- Kernel `dispatch`
    - Spy the `site`
    - Spy the `layout`
    - Initialize
        - `layout`
        - `site`
        - `segment`
    - Dispatch
        - `layout`
        - `site`
        - `segment`
    - Render
        - `segment`
        - `site`
        - `layout`
- Kernel `terminate`
    - Send response
    - Store debug information (environment `dev` only)

"Sites", "layouts" and "segments" can access some events (they can't access their own events, like `layout.pre_initialize` from `LayoutController`) via Component
[symfony/eventer-dispatcher](http://symfony.com/doc/current/components/event_dispatcher/introduction.html). Check out this list of possible events:

- `segment.pre_initialize`
- `segment.post_initialize`
- `segment.pre_dispatch`
- `segment.post_dispatch`
- `segment.pre_render`
- `segment.post_render`
- `layout.pre_initialize`
- `layout.post_initialize`
- `layout.pre_dispatch`
- `layout.post_dispatch`
- `layout.pre_render`
- `layout.post_render`
- `site.pre_initialize`
- `site.post_initialize`
- `site.pre_dispatch`
- `site.post_dispatch`
- `site.pre_render`
- `site.post_render`

```php
class BaseLayoutController extends LayoutController
{

    // use callback
    public function initialize()
    {
        $this->on('segment.post_initialize', function (SegmentInitializeEvent $event) {
            // ...
        });
    }

    // use the predefined method
    public function onSegmentPostInitialize(SegmentInitializeEvent $event)
    {
        $config = $event->getController()->getConfig();

        if ($config->has('something')) {
            $event->stopPropagation();

            // ...
        }
    }

}
```

# Contributors
- Marc Binder <marcandrebinder@gmail.com>


text:
package com.google.api.ads.dfp.jaxws.v201311;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Updates the specified {@link ProductTemplate}.
 *
 *             @param productTemplate the product template to update
 *             @return the updated product template
 *
 *
 *
Java class for updateProductTemplate element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="updateProductTemplate">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *           <element name="productTemplate" type="{https://www.google.com/apis/ads/publisher/v201311}ProductTemplate" minOccurs="0"/>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "productTemplate"
})
@XmlRootElement(name = "updateProductTemplate")
public class ProductTemplateServiceInterfaceupdateProductTemplate {

    protected ProductTemplate productTemplate;

    /**
     * Gets the value of the productTemplate property.
     *
     * @return
     *     possible object is
     *     {@link ProductTemplate }
     *
     */
    public ProductTemplate getProductTemplate() {
        return productTemplate;
    }

    /**
     * Sets the value of the productTemplate property.
     *
     * @param value
     *     allowed object is
     *     {@link ProductTemplate }
     *
     */
    public void setProductTemplate(ProductTemplate value) {
        this.productTemplate = value;
    }

}


text:
package org.broadinstitute.hellbender.tools.copynumber.formats;

import org.broadinstitute.hellbender.exceptions.UserException;
import org.broadinstitute.hellbender.utils.io.IOUtils;
import org.broadinstitute.hellbender.utils.text.XReadLines;
import org.broadinstitute.hellbender.utils.tsv.TableColumnCollection;
import org.broadinstitute.hellbender.utils.tsv.TableUtils;

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

public final class CopyNumberFormatsUtils {
    public static final String COMMENT_PREFIX = "@";    //SAMTextHeaderCodec.HEADER_LINE_START; we need TableReader to treat SAM header as comment lines
    public static final String DOUBLE_FORMAT = "%.6f";

    private CopyNumberFormatsUtils() {}

    public static String formatDouble(final double value) {
        return String.format(DOUBLE_FORMAT, value);
    }

    /**
     * Extracts column names from a TSV file
     */
    public static TableColumnCollection readColumnsFromHeader(final File inputFile) {
        IOUtils.canReadFile(inputFile);
        List<String> columns = null;
        try (final XReadLines reader = new XReadLines(inputFile)) {
            while (reader.hasNext()) {
                String nextLine = reader.next();
                if (!nextLine.startsWith(COMMENT_PREFIX)) {
                    columns = Arrays.asList(nextLine.split(TableUtils.COLUMN_SEPARATOR_STRING));
                    break;
                }
            }
        } catch (final IOException e) {
            throw new UserException.CouldNotReadInputFile(inputFile);
        }
        if (columns == null) {
            throw new UserException.BadInput(String.format(
                    "The input file %s does not have a header (starting with comment character %s).",
                    inputFile.getAbsolutePath(), COMMENT_PREFIX));
        }
        if (columns.stream().distinct().count() != columns.size()) {
            throw new UserException.BadInput("Column headers must all be unique.");
        }
        return new TableColumnCollection(columns);
    }
}


text:
package weixin.popular.support.msg.beans.receive;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

/**
 * 微信认证事件推送-年审通知消息
 *
 * @author Moyq5
 *
 */
@JacksonXmlRootElement(localName="xml")
public class MsgEAnnualRenew extends MsgE {
	private long ExpiredTime;

	public long getExpiredTime() {
		return ExpiredTime;
	}

	public void setExpiredTime(long expiredTime) {
		ExpiredTime = expiredTime;
	}

}


text:
package me.chanjar.jms.server.command.order;

import me.chanjar.jms.server.command.infras.CommandProcessor;
import me.chanjar.jms.server.command.infras.disruptor.CommandEventProducer;

public class OrderInsertCommandProcessor implements CommandProcessor<OrderInsertCommand> {

  private final CommandEventProducer<OrderInsertCommand>[] commandEventProducerList;

  private final int producerCount;

  public OrderInsertCommandProcessor(
      CommandEventProducer<OrderInsertCommand>[] commandEventProducerList) {
    this.commandEventProducerList = commandEventProducerList;
    this.producerCount = commandEventProducerList.length;
  }

  @Override
  public Class<OrderInsertCommand> getMatchClass() {
    return OrderInsertCommand.class;
  }

  @Override
  public void process(OrderInsertCommand command) {

    // 根据商品ID去模
    int index = (int) (command.getItemId() % (long) this.producerCount);
    commandEventProducerList[index].onData(command);

  }

}


text:
using System;

namespace UniverseEngine
{
    public class UniverseGeneratorDefault : UniverseGenerator
    {
        protected override void AddGalaxy()
        {
            int galaxyOrbits = random.Next(10, 20);

            ushort galaxySafeRadius = (ushort) (things[currentThing].safeRadius / 2);
            ushort solarSystemRadius = (ushort) (galaxySafeRadius / (galaxyOrbits * 2));

            for (int i = 0; i < galaxyOrbits; i++)
            {
                ushort solarSystemDistance = (ushort) ((galaxySafeRadius * i) / galaxyOrbits);

                int solarSystems = random.Next(
                    (Math.Max(i * 5, 1) + 1) / 2,
                    Math.Max(i * 5, 1) + 1
                    );

                short solarSystemOrbitalPeriod = (short) random.Next(120, 240);
                if (random.Next(0, 2) == 0)
                    solarSystemOrbitalPeriod = (short) -solarSystemOrbitalPeriod;

                for (int j = 0; j < solarSystems; j++)
                {
                    ushort solarSystemAngle = (ushort) ((36000 * j) / solarSystems);

                    PushThing(ThingType.SolarSystem, solarSystemAngle, solarSystemDistance, 0, solarSystemOrbitalPeriod, 0, solarSystemRadius, 0);
                    {
                        int suns = random.Next(1, 3);

                        ushort solarSystemSafeRadius = things[currentThing].safeRadius;

                        ushort sunRadius = (ushort) random.Next(
                            (solarSystemRadius / 8) / 2,
                            (solarSystemRadius / 8)
                            );

                        if (suns == 1)
                        {
                            PushThing(ThingType.Sun, 0, 0, 0, 0, Planet.GetClosestValidRadius(sunRadius), 0, random.Next());
                            PopThing();
                        }
                        else
                        {
                            ushort sunDistance = (ushort) (sunRadius * 4 / 3);
                            short sunOrbitalPerdiod = (short) random.Next(30, 60);
                            if (random.Next(0, 2) == 0)
                                sunOrbitalPerdiod = (short) -sunOrbitalPerdiod;

                            for (int k = 0; k < suns; k++)
                            {
                                ushort sunAngle = (ushort) ((36000 * k) / suns);

                                PushThing(ThingType.Sun, sunAngle, sunDistance, 0, sunOrbitalPerdiod, Planet.GetClosestValidRadius(sunRadius), 0, random.Next());
                                PopThing();
                            }
                        }

                        int planetsOrbits = random.Next(1, 8);

                        ushort planetSafeRadius = (ushort) ((solarSystemSafeRadius - sunRadius * 6) / (planetsOrbits * 2));

                        for (int l = 0; l < planetsOrbits; l++)
                        {
                            ushort planetDistance = (ushort) (sunRadius * 6 + ((solarSystemSafeRadius - sunRadius * 6) * l) / planetsOrbits);

                            ushort planetAngle = (ushort) random.Next(0, 36000);

                            short planetRotationPeriod = (short) random.Next(30, 60);
                            if (random.Next(0, 2) == 0)
                                planetRotationPeriod = (short) -planetRotationPeriod;

                            short planetOrbitationPeriod = (short) random.Next(30, 60);
                            if (random.Next(0, 2) == 0)
                                planetOrbitationPeriod = (short) -planetOrbitationPeriod;

                            ushort planetRadius = (ushort) random.Next(planetSafeRadius / 16, planetSafeRadius / 9);

                            PushThing(ThingType.Planet, planetAngle, planetDistance, planetRotationPeriod, planetOrbitationPeriod, Planet.GetClosestValidRadius(planetRadius), planetSafeRadius, random.Next());
                            PopThing();
                        }

                    }
                    PopThing();
                }
            }
        }
    }
}


text:
from pyaff4 import aff4
from pyaff4 import aff4_directory
try:
    from pyaff4 import aff4_cloud
except ImportError:
    pass

from pyaff4 import aff4_file
from pyaff4 import aff4_image
from pyaff4 import aff4_map
from pyaff4 import zip


text:
package org.vngx.jsch.userauth;

import org.vngx.jsch.exception.JSchException;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Implementation of JSchException for partial authentication
 * exceptions.  When a user authentication method receives a
 * SSH_MSG_USERAUTH_FAILURE response from the server, the server may pass back
 * a list of user authentication methods which can still proceed.  This response
 * generates a JSchPartialAuthException which contains the parsed
 * set of user auth methods.
 *
 * @author Atsuhiko Yamanaka
 * @author Michael Laudati
 */
final class PartialAuthException extends JSchException {

	/** Set of user authentication methods which can proceed from server. */
	private final Set<String> _nameList;

	/**
	 * Creates a new instance of JSchPartialAuthException with the
	 * specified name list of user authentication methods which can proceed.
	 *
	 * @param nameList of auth methods from server
	 */
	PartialAuthException(String nameList) {
		if( nameList != null ) {
			_nameList = new LinkedHashSet<String>(Arrays.asList(nameList.split(",")));
		} else {
			_nameList = Collections.emptySet();
		}
	}

	/**
	 * Set of server supported authentication methods which can proceed.
	 *
	 * @return set of server supported user auth methods
	 */
	Set<String> getUserAuthMethods() {
		return _nameList;
	}

}


text:
swoole_http2_client_coro: http2 ping
--SKIPIF--
<?php require __DIR__ . '/../include/skipif.inc';
skip_if_offline();
?>
--FILE--
<?php
require __DIR__ . '/../include/bootstrap.php';
Co::set(['log_level' => SWOOLE_LOG_WARNING]);
go(function () {
    $domain = 'nghttp2.org';
    $cli = new Swoole\Coroutine\Http2\Client($domain, 443, true);
    $cli->set([
        'timeout' => 5,
        'ssl_host_name' => $domain
    ]);
    if (!$cli->connect()) {
        exit; // we can't connect to this website without proxy in China so we skip it.
    }
    $ret = $cli->ping();
    Assert::assert($ret);
    Co::sleep(0.5);
    Assert::greaterThan($cli->send(new Swoole\Http2\Request), 0);
    $response = $cli->recv();
    if (!$response && $cli->errCode === SOCKET_ETIMEDOUT) {
        exit;
    }
    Assert::contains($response->data, 'nghttp2');
});
?>
--EXPECT--


text:
package org.ppwcode.value_III.location.postalcode;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.ppwcode.value_III.id11n.AbstractRegexIdentifierTest;
import org.ppwcode.value_III.id11n.Identifier;
import org.ppwcode.value_III.id11n.IdentifierWellformednessException;
import org.ppwcode.value_III.location.Country;
import org.ppwcode.value_III.location.CountryEditor;
import org.ppwcode.value_III.location.PostalAddress;
import org.ppwcode.value_III.location.PostalCode;
import org.ppwcode.vernacular.value_III.ValueException;

public class BePostalCodeTest extends AbstractRegexIdentifierTest {

  @Override
  @Before
  public void setUp() throws Exception {
    List<BePostalCode> s = new ArrayList<BePostalCode>();
    BePostalCode subject = new BePostalCode("2500"); // Lier
    s.add(subject);
    subject = new BePostalCode("2000");
    s.add(subject);
    subject = new BePostalCode("1000");
    s.add(subject);
    subject = new BePostalCode("1040");
    s.add(subject);
    subject = new BePostalCode("4000");
    s.add(subject);
    subject = new BePostalCode("6900");
    s.add(subject);
    $subjects = s;
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<? extends BePostalCode> subjects() {
    return (List<? extends BePostalCode>) $subjects;
  }

  // Cannot use the super directly
  protected void assertInvariants(BePostalCode subject) {
    super.assertInvariants((Identifier) subject);
    Assert.assertEquals(BePostalCode.REGEX_PATTERN.pattern(), BePostalCode.REGEX_PATTERN_STRING);
    Assert.assertEquals(subject.getCountry(), Country.VALUES.get("BE"));
  }

  @Test(expected = IdentifierWellformednessException.class)
  public void testBePostalCode1() throws IdentifierWellformednessException {
    new BePostalCode("0123456789");
  }

  @Test
  public void testBePostalCode2() throws IdentifierWellformednessException {
    String identifier = "2500"; // Lier
    BePostalCode subject = new BePostalCode("2500");
    testBePostalCode(subject, identifier);
  }

  @Test(expected = IdentifierWellformednessException.class)
  public void testBePostalCode2b() throws IdentifierWellformednessException {
    String identifier = "2500a";
    BePostalCode subject = new BePostalCode("2500a");
    testBePostalCode(subject, identifier);
  }

  @Test(expected = IdentifierWellformednessException.class)
  public void testBePostalCode3() throws IdentifierWellformednessException {
    new BePostalCode("BE 2500");
  }

  @Test(expected = IdentifierWellformednessException.class)
  public void testBePostalCode4() throws IdentifierWellformednessException {
    new BePostalCode(" 2500");
  }

  @Test(expected = IdentifierWellformednessException.class)
  public void testBePostalCode5() throws IdentifierWellformednessException {
    new BePostalCode("25.00");
  }

  @Test
  public void testBePostalCode6() throws IdentifierWellformednessException {
    String identifier = "2000";
    BePostalCode subject = new BePostalCode(identifier);
    testBePostalCode(subject, identifier);
  }

  private void testBePostalCode(BePostalCode subject, String identifier) {
    Assert.assertEquals(identifier, subject.getIdentifier());
    assertInvariants(subject);
  }

  @Test
  public void testLocalizedAddressRepresentation() throws ValueException {
    for (BePostalCode subject : subjects()) {
      testLocalizedAddressRepresentation(subject, new PostalAddress(subject, new Locale("NL", "be"), "Lier",
          "Duwijckstraat 17"));
      assertInvariants(subject);
      testLocalizedAddressRepresentation(subject, new PostalAddress(subject, new Locale("FR", "be"), "Bruxelles",
          "Henry Jaspaardlaan 128"));
      assertInvariants(subject);
    }
  }

  private void testLocalizedAddressRepresentation(final BePostalCode subject, final PostalAddress postalAddress) {
    String result = subject.localizedAddressRepresentation(postalAddress);

    CountryEditor ce = new CountryEditor();
    ce.setDisplayLocale(postalAddress.getLocale());
    ce.setValue(subject.getCountry());

    Assert.assertNotNull(result);
    Assert.assertTrue(result != "");
    Assert.assertTrue(result.contains(postalAddress.getStreetAddress()));
    Assert.assertTrue(result.contains(postalAddress.getPostalCode().getIdentifier()));
    Assert.assertTrue(result.contains(postalAddress.getCity()));
    Assert.assertTrue(result.equals(postalAddress.getStreetAddress() + PostalCode.EOL + subject.getIdentifier() + " "
        + postalAddress.getCity() + PostalCode.EOL + ce.getLabel()));
  }
}


text:
<?php

namespace Drupal\Tests\Core\Extension;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\Extension;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\Extension\Exception\UnknownExtensionException;
use Drupal\Tests\UnitTestCase;

/**
 * @coversDefaultClass \Drupal\Core\Extension\ModuleHandler
 * @runTestsInSeparateProcesses
 *
 * @group Extension
 */
class ModuleHandlerTest extends UnitTestCase {

  /**
   * The mocked cache backend.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface|\PHPUnit\Framework\MockObject\MockObject
   */
  protected $cacheBackend;

  /**
   * {@inheritdoc}
   *
   * @covers ::__construct
   */
  protected function setUp(): void {
    parent::setUp();
    // We can mock the cache handler here, but not the module handler.
    $this->cacheBackend = $this->createMock(CacheBackendInterface::class);
  }

  /**
   * Get a module handler object to test.
   *
   * Since we have to run these tests in separate processes, we have to use
   * test objects which are serializable. Since ModuleHandler will populate
   * itself with Extension objects, and since Extension objects will try to
   * access DRUPAL_ROOT when they're unserialized, we can't store our mocked
   * ModuleHandler objects as a property in unit tests. They must be generated
   * by the test method by calling this method.
   *
   * @return \Drupal\Core\Extension\ModuleHandler
   *   The module handler to test.
   */
  protected function getModuleHandler() {
    $module_handler = new ModuleHandler($this->root, [
      'module_handler_test' => [
        'type' => 'module',
        'pathname' => 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test/module_handler_test.info.yml',
        'filename' => 'module_handler_test.module',
      ],
    ], $this->cacheBackend);
    return $module_handler;
  }

  /**
   * Tests loading a module.
   *
   * @covers ::load
   */
  public function testLoadModule() {
    $module_handler = $this->getModuleHandler();
    $this->assertFalse(function_exists('module_handler_test_hook'));
    $this->assertTrue($module_handler->load('module_handler_test'));
    $this->assertTrue(function_exists('module_handler_test_hook'));

    $module_handler->addModule('module_handler_test_added', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_added');
    $this->assertFalse(function_exists('module_handler_test_added_hook'), 'Function does not exist before being loaded.');
    $this->assertTrue($module_handler->load('module_handler_test_added'));
    $this->assertTrue(function_exists('module_handler_test_added_helper'), 'Function exists after being loaded.');
    $this->assertTrue($module_handler->load('module_handler_test_added'));

    $this->assertFalse($module_handler->load('module_handler_test_dne'), 'Non-existent modules returns false.');
  }

  /**
   * Tests loading all modules.
   *
   * @covers ::loadAll
   */
  public function testLoadAllModules() {
    $module_handler = $this->getModuleHandler();
    $module_handler->addModule('module_handler_test_all1', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_all1');
    $module_handler->addModule('module_handler_test_all2', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_all2');
    $this->assertFalse(function_exists('module_handler_test_all1_hook'), 'Function does not exist before being loaded.');
    $this->assertFalse(function_exists('module_handler_test_all2_hook'), 'Function does not exist before being loaded.');
    $module_handler->loadAll();
    $this->assertTrue(function_exists('module_handler_test_all1_hook'), 'Function exists after being loaded.');
    $this->assertTrue(function_exists('module_handler_test_all2_hook'), 'Function exists after being loaded.');
  }

  /**
   * Tests reload method.
   *
   * @covers ::reload
   */
  public function testModuleReloading() {
    $module_handler = $this->getMockBuilder(ModuleHandler::class)
      ->setConstructorArgs([
        $this->root,
        [
          'module_handler_test' => [
            'type' => 'module',
            'pathname' => 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test/module_handler_test.info.yml',
            'filename' => 'module_handler_test.module',
          ],
        ], $this->cacheBackend,
      ])
      ->onlyMethods(['load'])
      ->getMock();
    $module_handler->expects($this->exactly(3))
      ->method('load')
      ->withConsecutive(
        // First reload.
        ['module_handler_test'],
        // Second reload.
        ['module_handler_test'],
        ['module_handler_test_added'],
      );
    $module_handler->reload();
    $module_handler->addModule('module_handler_test_added', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_added');
    $module_handler->reload();
  }

  /**
   * Tests isLoaded accessor.
   *
   * @covers ::isLoaded
   */
  public function testIsLoaded() {
    $module_handler = $this->getModuleHandler();
    $this->assertFalse($module_handler->isLoaded());
    $module_handler->loadAll();
    $this->assertTrue($module_handler->isLoaded());
  }

  /**
   * Confirm we get back the modules set in the constructor.
   *
   * @covers ::getModuleList
   */
  public function testGetModuleList() {
    $this->assertEquals($this->getModuleHandler()->getModuleList(), [
      'module_handler_test' => new Extension($this->root, 'module', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test/module_handler_test.info.yml', 'module_handler_test.module'),
    ]);
  }

  /**
   * Confirm we get back a module from the module list.
   *
   * @covers ::getModule
   */
  public function testGetModuleWithExistingModule() {
    $this->assertEquals($this->getModuleHandler()->getModule('module_handler_test'), new Extension($this->root, 'module', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test/module_handler_test.info.yml', 'module_handler_test.module'));
  }

  /**
   * @covers ::getModule
   */
  public function testGetModuleWithNonExistingModule() {
    $this->expectException(UnknownExtensionException::class);
    $this->getModuleHandler()->getModule('claire_alice_watch_my_little_pony_module_that_does_not_exist');
  }

  /**
   * Ensure setting the module list replaces the module list and resets internal structures.
   *
   * @covers ::setModuleList
   */
  public function testSetModuleList() {
    $fixture_module_handler = $this->getModuleHandler();
    $module_handler = $this->getMockBuilder(ModuleHandler::class)
      ->setConstructorArgs([
        $this->root, [], $this->cacheBackend,
      ])
      ->onlyMethods(['resetImplementations'])
      ->getMock();

    // Ensure we reset implementations when settings a new modules list.
    $module_handler->expects($this->once())->method('resetImplementations');

    // Make sure we're starting empty.
    $this->assertEquals([], $module_handler->getModuleList());

    // Replace the list with a prebuilt list.
    $module_handler->setModuleList($fixture_module_handler->getModuleList());

    // Ensure those changes are stored.
    $this->assertEquals($fixture_module_handler->getModuleList(), $module_handler->getModuleList());
  }

  /**
   * Tests adding a module.
   *
   * @covers ::addModule
   * @covers ::add
   */
  public function testAddModule() {

    $module_handler = $this->getMockBuilder(ModuleHandler::class)
      ->setConstructorArgs([
        $this->root, [], $this->cacheBackend,
      ])
      ->onlyMethods(['resetImplementations'])
      ->getMock();

    // Ensure we reset implementations when settings a new modules list.
    $module_handler->expects($this->once())->method('resetImplementations');

    $module_handler->addModule('module_handler_test', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test');
    $this->assertTrue($module_handler->moduleExists('module_handler_test'));
  }

  /**
   * Tests adding a profile.
   *
   * @covers ::addProfile
   * @covers ::add
   */
  public function testAddProfile() {

    $module_handler = $this->getMockBuilder(ModuleHandler::class)
      ->setConstructorArgs([
        $this->root, [], $this->cacheBackend,
      ])
      ->onlyMethods(['resetImplementations'])
      ->getMock();

    // Ensure we reset implementations when settings a new modules list.
    $module_handler->expects($this->once())->method('resetImplementations');

    // @todo this should probably fail since its a module not a profile.
    $module_handler->addProfile('module_handler_test', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test');
    $this->assertTrue($module_handler->moduleExists('module_handler_test'));
  }

  /**
   * Tests module exists returns correct module status.
   *
   * @covers ::moduleExists
   */
  public function testModuleExists() {
    $module_handler = $this->getModuleHandler();
    $this->assertTrue($module_handler->moduleExists('module_handler_test'));
    $this->assertFalse($module_handler->moduleExists('module_handler_test_added'));
  }

  /**
   * @covers ::loadAllIncludes
   */
  public function testLoadAllIncludes() {
    $this->assertTrue(TRUE);
    $module_handler = $this->getMockBuilder(ModuleHandler::class)
      ->setConstructorArgs([
        $this->root,
        [
          'module_handler_test' => [
            'type' => 'module',
            'pathname' => 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test/module_handler_test.info.yml',
            'filename' => 'module_handler_test.module',
          ],
        ], $this->cacheBackend,
      ])
      ->onlyMethods(['loadInclude'])
      ->getMock();

    // Ensure we reset implementations when settings a new modules list.
    $module_handler->expects($this->once())->method('loadInclude');
    $module_handler->loadAllIncludes('hook');
  }

  /**
   * @covers ::loadInclude
   *
   * Note we load code, so isolate the test.
   *
   * @runInSeparateProcess
   * @preserveGlobalState disabled
   */
  public function testLoadInclude() {
    $module_handler = $this->getModuleHandler();
    // Include exists.
    $this->assertEquals(__DIR__ . '/modules/module_handler_test/hook_include.inc', $module_handler->loadInclude('module_handler_test', 'inc', 'hook_include'));
    $this->assertTrue(function_exists('module_handler_test_hook_include'));
    // Include doesn't exist.
    $this->assertFalse($module_handler->loadInclude('module_handler_test', 'install'));
  }

  /**
   * Tests invoke methods when module is enabled.
   *
   * @covers ::invoke
   */
  public function testInvokeModuleEnabled() {
    $module_handler = $this->getModuleHandler();
    $this->assertTrue($module_handler->invoke('module_handler_test', 'hook', [TRUE]), 'Installed module runs hook.');
    $this->assertFalse($module_handler->invoke('module_handler_test', 'hook', [FALSE]), 'Installed module runs hook.');
    $this->assertNull($module_handler->invoke('module_handler_test_fake', 'hook', [FALSE]), 'Installed module runs hook.');
  }

  /**
   * Tests implementations methods when module is enabled.
   *
   * @covers ::hasImplementations
   * @covers ::loadAllIncludes
   */
  public function testImplementsHookModuleEnabled() {
    $module_handler = $this->getModuleHandler();
    $this->assertTrue($module_handler->hasImplementations('hook', 'module_handler_test'), 'Installed module implementation found.');

    $module_handler->addModule('module_handler_test_added', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_added');
    $this->assertTrue($module_handler->hasImplementations('hook', 'module_handler_test_added'), 'Runtime added module with implementation in include found.');

    $module_handler->addModule('module_handler_test_no_hook', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_no_hook');
    $this->assertFalse($module_handler->hasImplementations('hook', 'module_handler_test_no_hook'), 'Missing implementation not found.');
  }

  /**
   * Tests deprecation of the ::getImplementations method.
   *
   * @covers ::getImplementations
   * @covers ::getImplementationInfo
   * @covers ::buildImplementationInfo
   *
   * @group legacy
   */
  public function testGetImplementations() {
    $this->expectDeprecation('ModuleHandlerInterface::getImplementations() is deprecated in drupal:9.4.0 and is removed from drupal:10.0.0. Instead you should use ModuleHandlerInterface::invokeAllWith() for hook invocations, or you should use ModuleHandlerInterface::hasImplementations() to determine if hooks implementations exist. See https://www.drupal.org/node/3000490');
    $this->assertEquals(['module_handler_test'], $this->getModuleHandler()->getImplementations('hook'));
  }

  /**
   * Tests deprecation of the ::implementsHook method.
   *
   * @covers ::implementsHook
   *
   * @group legacy
   */
  public function testImplementsHook() {
    $this->expectDeprecation('ModuleHandlerInterface::implementsHook() is deprecated in drupal:9.4.0 and is removed from drupal:10.0.0. Instead you should use ModuleHandlerInterface::hasImplementations()  with the $modules argument. See https://www.drupal.org/node/3000490');
    $this->assertTrue($this->getModuleHandler()->implementsHook('module_handler_test', 'hook'));
  }

  /**
   * Tests hasImplementations.
   *
   * @covers ::hasImplementations
   */
  public function testHasImplementations() {
    $module_handler = $this->getMockBuilder(ModuleHandler::class)
      ->setConstructorArgs([$this->root, [], $this->cacheBackend])
      ->onlyMethods(['buildImplementationInfo'])
      ->getMock();
    $module_handler->expects($this->exactly(2))
      ->method('buildImplementationInfo')
      ->with('hook')
      ->willReturnOnConsecutiveCalls(
        [],
        ['mymodule' => FALSE],
      );

    // ModuleHandler::buildImplementationInfo mock returns no implementations.
    $this->assertFalse($module_handler->hasImplementations('hook'));

    // Reset static caches.
    $module_handler->resetImplementations();

    // ModuleHandler::buildImplementationInfo mock returns an implementation.
    $this->assertTrue($module_handler->hasImplementations('hook'));
  }

  /**
   * Tests getImplementations.
   *
   * @covers ::invokeAllWith
   */
  public function testCachedGetImplementations() {
    $this->cacheBackend->expects($this->exactly(1))
      ->method('get')
      ->will($this->onConsecutiveCalls(
        (object) ['data' => ['hook' => ['module_handler_test' => 'test']]]
      ));

    // Ensure buildImplementationInfo doesn't get called and that we work off cached results.
    $module_handler = $this->getMockBuilder(ModuleHandler::class)
      ->setConstructorArgs([
        $this->root, [
          'module_handler_test' => [
            'type' => 'module',
            'pathname' => 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test/module_handler_test.info.yml',
            'filename' => 'module_handler_test.module',
          ],
        ], $this->cacheBackend,
      ])
      ->onlyMethods(['buildImplementationInfo', 'loadInclude'])
      ->getMock();
    $module_handler->load('module_handler_test');

    $module_handler->expects($this->never())->method('buildImplementationInfo');
    $module_handler->expects($this->once())->method('loadInclude');
    $implementors = [];
    $module_handler->invokeAllWith(
      'hook',
      function (callable $hook, string $module) use (&$implementors) {
        $implementors[] = $module;
      }
    );
    $this->assertEquals(['module_handler_test'], $implementors);
  }

  /**
   * Tests getImplementations.
   *
   * @covers ::invokeAllWith
   */
  public function testCachedGetImplementationsMissingMethod() {
    $this->cacheBackend->expects($this->exactly(1))
      ->method('get')
      ->will($this->onConsecutiveCalls((object) [
        'data' => [
          'hook' => [
            'module_handler_test' => [],
            'module_handler_test_missing' => [],
          ],
        ],
      ]));

    // Ensure buildImplementationInfo doesn't get called and that we work off cached results.
    $module_handler = $this->getMockBuilder(ModuleHandler::class)
      ->setConstructorArgs([
        $this->root, [
          'module_handler_test' => [
            'type' => 'module',
            'pathname' => 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test/module_handler_test.info.yml',
            'filename' => 'module_handler_test.module',
          ],
        ], $this->cacheBackend,
      ])
      ->onlyMethods(['buildImplementationInfo'])
      ->getMock();
    $module_handler->load('module_handler_test');

    $module_handler->expects($this->never())->method('buildImplementationInfo');
    $implementors = [];
    $module_handler->invokeAllWith(
      'hook',
      function (callable $hook, string $module) use (&$implementors) {
        $implementors[] = $module;
      }
    );
    $this->assertEquals(['module_handler_test'], $implementors);
  }

  /**
   * Tests invoke all.
   *
   * @covers ::invokeAll
   */
  public function testInvokeAll() {
    $module_handler = $this->getModuleHandler();
    $module_handler->addModule('module_handler_test_all1', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_all1');
    $module_handler->addModule('module_handler_test_all2', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_all2');
    $this->assertEquals([TRUE, TRUE, TRUE], $module_handler->invokeAll('hook', [TRUE]));
  }

  /**
   * Tests that write cache calls through to cache library correctly.
   *
   * @covers ::writeCache
   */
  public function testWriteCache() {
    $module_handler = $this->getModuleHandler();
    $this->cacheBackend
      ->expects($this->exactly(2))
      ->method('get')
      ->will($this->returnValue(NULL));
    $this->cacheBackend
      ->expects($this->exactly(2))
      ->method('set')
      ->with($this->logicalOr('module_implements', 'hook_info'));
    $module_handler->invokeAllWith('hook', function (callable $hook, string $module) {});
    $module_handler->writeCache();
  }

  /**
   * Tests hook_hook_info() fetching through getHookInfo().
   *
   * @covers ::getHookInfo
   * @covers ::buildHookInfo
   */
  public function testGetHookInfo() {
    $module_handler = $this->getModuleHandler();
    // Set up some synthetic results.
    $this->cacheBackend
      ->expects($this->exactly(2))
      ->method('get')
      ->will($this->onConsecutiveCalls(
        NULL,
        (object) ['data' => ['hook_foo' => ['group' => 'hook']]]
      ));

    // Results from building from mocked environment.
    $this->assertEquals([
      'hook' => ['group' => 'hook'],
    ], $module_handler->getHookInfo());

    // Reset local cache so we get our synthetic result from the cache handler.
    $module_handler->resetImplementations();
    $this->assertEquals([
      'hook_foo' => ['group' => 'hook'],
    ], $module_handler->getHookInfo());
  }

  /**
   * Tests internal implementation cache reset.
   *
   * @covers ::resetImplementations
   */
  public function testResetImplementations() {
    $module_handler = $this->getModuleHandler();
    // Prime caches
    $module_handler->invokeAllWith('hook', function (callable $hook, string $module) {});
    $module_handler->getHookInfo();

    // Reset all caches internal and external.
    $this->cacheBackend
      ->expects($this->once())
      ->method('delete')
      ->with('hook_info');
    $this->cacheBackend
      ->expects($this->exactly(2))
      ->method('set')
      // reset sets module_implements to array() and getHookInfo later
      // populates hook_info.
      ->with($this->logicalOr('module_implements', 'hook_info'));
    $module_handler->resetImplementations();

    // Request implementation and ensure hook_info and module_implements skip
    // local caches.
    $this->cacheBackend
      ->expects($this->exactly(2))
      ->method('get')
      ->with($this->logicalOr('module_implements', 'hook_info'));
    $module_handler->invokeAllWith('hook', function (callable $hook, string $module) {});
  }

  /**
   * @covers ::getModuleDirectories
   */
  public function testGetModuleDirectories() {
    $module_handler = $this->getModuleHandler();
    $module_handler->setModuleList([]);
    $module_handler->addModule('node', 'core/modules/node');
    $this->assertEquals(['node' => $this->root . '/core/modules/node'], $module_handler->getModuleDirectories());
  }

}


text:
using System.Collections.Generic;

namespace IxMilia.Iges.Entities
{
    public class IgesEllipsoid : IgesEntity
    {
        public override IgesEntityType EntityType { get { return IgesEntityType.Ellipsoid; } }

        public double XAxisLength { get; set; }
        public double YAxisLength { get; set; }
        public double ZAxisLength { get; set; }
        public IgesPoint Center { get; set; }
        public IgesVector XAxis { get; set; }
        public IgesVector ZAxis { get; set; }

        public IgesEllipsoid()
        {
            EntityUseFlag = IgesEntityUseFlag.Geometry;
            Center = IgesPoint.Origin;
            XAxis = IgesVector.XAxis;
            ZAxis = IgesVector.ZAxis;
        }

        internal override int ReadParameters(List<string> parameters, IgesReaderBinder binder)
        {
            int index = 0;
            XAxisLength = Double(parameters, index++);
            YAxisLength = Double(parameters, index++);
            ZAxisLength = Double(parameters, index++);
            Center = Point3(parameters, ref index);
            XAxis = VectorOrDefault(parameters, ref index, IgesVector.XAxis);
            ZAxis = VectorOrDefault(parameters, ref index, IgesVector.ZAxis);
            return 12;
        }

        internal override void WriteParameters(List<object> parameters, IgesWriterBinder binder)
        {
            parameters.Add(XAxisLength);
            parameters.Add(YAxisLength);
            parameters.Add(ZAxisLength);
            parameters.Add(Center.X);
            parameters.Add(Center.Y);
            parameters.Add(Center.Z);
            parameters.Add(XAxis.X);
            parameters.Add(XAxis.Y);
            parameters.Add(XAxis.Z);
            parameters.Add(ZAxis.X);
            parameters.Add(ZAxis.Y);
            parameters.Add(ZAxis.Z);
        }
    }
}


text:
#import <GPUToolsAnalysis/DYAnalyzerHeuristic.h>

// Not exported
@interface DYAnalyzerHeuristic_InvalidBufferUsage : DYAnalyzerHeuristic
{
    BOOL readPixelsHasOccurred;
    BOOL hasReportedEnableDepthTestWithoutDepthBuffer;
    BOOL hasReportedEnableStencilTestWithoutStencilBuffer;
    BOOL hasReportedDrawAfterReadPixels;
    int enableDepthTestFuncIndex;
    int enableStencilTestFuncIndex;
    int readPixelsFunctionIndex;
    int framebufferBindFuncIndex;
    int prevWidth;
    int prevHeight;
    int prevAttachmentPoint;
    int prevNumMultisamples;
    const FramebufferAttachment_85593ca2 *_pDepthAttachment;
}

+ (BOOL)_internalFormatRequiresFixedOrFloat:(int)arg1;
+ (BOOL)_internalFormatRequiresUnsignedInt:(int)arg1;
+ (BOOL)_internalFormatRequiresSignedInt:(int)arg1;
+ (const FramebufferAttachment_85593ca2 *)_getAttachment:(ContextStateMirror_efb9dfa5 *)arg1 buffer:(int)arg2 drawBuffer:(int)arg3;
+ (id)identifier;
- (void)reportAttachmentInternalFormatIsNotTextureFilterable:(const struct Function *)arg1 framebufferID:(int)arg2 attachmentPoint:(int)arg3 internalFormat:(int)arg4;
- (void)reportColorAttachmentInternalFormatIsNotColorRenderable:(const struct Function *)arg1 framebufferID:(int)arg2 attachmentPoint:(int)arg3;
- (void)reportStencilAttachmentInternalFormatIsNotStencilRenderable:(const struct Function *)arg1 framebufferID:(int)arg2;
- (void)reportDepthAttachmentInternalFormatIsNotDepthRenderable:(const struct Function *)arg1 framebufferID:(int)arg2;
- (void)reportClearBufferInvalidColorBuffer:(const struct Function *)arg1 drawBuffer:(int)arg2 formatType:(int)arg3;
- (void)reportClearBufferInvalidBuffer:(const struct Function *)arg1 bufferType:(int)arg2;
- (void)reportDepthStencilAttachmentsAreNotSameImage:(const struct Function *)arg1 framebufferID:(int)arg2 attachmentObjectID:(int)arg3;
- (void)reportTextureLayerAttachmentExceedsDepth:(const struct Function *)arg1 framebufferID:(int)arg2 attachmentObjectID:(int)arg3 texLayer:(int)arg4 texDepth:(int)arg5;
- (void)reportNoAttachments:(const struct Function *)arg1 framebufferID:(int)arg2;
- (void)reportAttachmentNumMultisampleMismatch:(const struct Function *)arg1 framebufferID:(int)arg2 attachmentPoint:(int)arg3 attachmentNumMultisamples:(int)arg4 prevAttachmentPoint:(int)arg5 prevAttachmentNumMultisamples:(int)arg6;
- (void)reportAttachmentSizeMismatch:(const struct Function *)arg1 framebufferID:(int)arg2 attachmentPoint:(int)arg3 attachmentWidth:(int)arg4 attachmentHeight:(int)arg5 prevAttachmentPoint:(int)arg6 prevWidth:(int)arg7 prevHeight:(int)arg8;
- (void)reportZeroSizedAttachment:(const struct Function *)arg1 framebufferID:(int)arg2 attachmentPoint:(int)arg3 attachmentObjectType:(int)arg4 attachmentObjectID:(int)arg5;
- (void)reportNonExistentAttachment:(const struct Function *)arg1 framebufferID:(int)arg2 attachmentPoint:(int)arg3 attachmentObjectType:(int)arg4 attachmentObjectID:(int)arg5;
- (void)reportReadPixelsSuboptimalFormat:(const struct Function *)arg1;
- (void)reportReadPixelsSuboptimalDimensions:(const struct Function *)arg1;
- (void)reportReadPixelsSuboptimalPacking:(const struct Function *)arg1;
- (void)reportDrawCallAfterReadPixels:(const struct Function *)arg1;
- (void)reportEnableStencilTestWithoutStencilBuffer:(const struct Function *)arg1;
- (void)reportEnableDepthTestWithoutDepthBuffer:(const struct Function *)arg1;
- (void)startNewRenderTarget;
- (void)endBlock:(int)arg1;
- (void)startBlock:(int)arg1;
- (BOOL)_isES3SpecStencilRenderableFormat:(int)arg1;
- (BOOL)_isES3SpecDepthRenderableFormat:(int)arg1;
- (BOOL)_isFormatColorRenderable:(int)arg1;
- (void)_checkColorBuffer:(const struct Function *)arg1 context:(ContextStateMirror_efb9dfa5 *)arg2 drawBuffer:(int)arg3 hasFormatType:(int)arg4;
- (void)_checkAttachment:(const struct Function *)arg1 context:(ContextStateMirror_efb9dfa5 *)arg2 framebufferID:(int)arg3 attachmentPoint:(int)arg4 attachment:(const FramebufferAttachment_85593ca2 *)arg5;
- (void)verifyFBOAttachmentSetup:(const struct Function *)arg1 framebufferTarget:(int)arg2 mask:(unsigned int)arg3;
- (void)processFunction:(const struct Function *)arg1 stateMirrorRetCode:(unsigned int)arg2;
- (id)init;

@end


text:
using System.Collections.Generic;
using System.ServiceModel;
using EspaceClient.BackOffice.Infrastructure.Context;
using EspaceClient.FrontOffice.Domaine;

namespace EspaceClient.BackOffice.Services.Contracts
{
    /// <summary>
    /// Définition des services des Contact.
    /// </summary>
    [ServiceContract]
    public partial interface IServiceContact
    {

        [OperationContract]
        IEnumerable<ContactDto> GetAll(WebContext context);

    }
}


text:
<?php

namespace App\Language\Admin\English\Widget;

class Featured {
	public static function lang() {
		// Heading
		$_['lang_heading_title']    = 'Featured';

		// Text
		$_['lang_text_widget']      = 'Widgets';
		$_['lang_text_success']     = 'Success: You have modified widget featured.';

		// Entry
		$_['lang_entry_product']    = 'Products:
(Autocomplete)';
		$_['lang_entry_limit']      = 'Limit:';
		$_['lang_entry_image']      = 'Image (W x H) and Resize Type:';
		$_['lang_entry_layout']     = 'Layout:';
		$_['lang_entry_position']   = 'Position:';
		$_['lang_entry_status']     = 'Status:';
		$_['lang_entry_sort_order'] = 'Sort Order:';

		// Error
		$_['lang_error_permission'] = 'Warning: You do not have permission to modify widget featured.';
		$_['lang_error_image']      = 'Image width & height dimensions required.';

		return $_;
	}
}


text:
#include "ircmessage.h"
#include "ircconnection.h"
#include <QtTest/QtTest>

static const QByteArray MSG_32_5("Vestibulum eu libero eget metus.");
static const QByteArray MSG_64_9("Phasellus enim dui, sodales sed tincidunt quis, ultricies metus.");
static const QByteArray MSG_128_19("Ut porttitor volutpat tristique. Aenean semper ligula eget nulla condimentum tempor in quis felis. Sed sem diam, tincidunt amet.");
static const QByteArray MSG_256_37("Vestibulum quis lorem velit, a varius augue. Suspendisse risus augue, ultricies at convallis in, elementum in velit. Fusce fermentum congue augue sit amet dapibus. Fusce ultrices urna ut tortor laoreet a aliquet elit lobortis. Suspendisse volutpat posuere.");
static const QByteArray MSG_512_75("Nam leo risus, accumsan a sagittis eget, posuere eu velit. Morbi mattis auctor risus, vel consequat massa pulvinar nec. Proin aliquam convallis elit nec egestas. Pellentesque accumsan placerat augue, id volutpat nibh dictum vel. Aenean venenatis varius feugiat. Nullam molestie, ipsum id dignissim vulputate, eros urna vestibulum massa, in vehicula lacus nisi vitae risus. Ut nunc nunc, venenatis a mattis auctor, dictum et sem. Nulla posuere libero ut tortor elementum egestas. Aliquam egestas suscipit posuere.");

class tst_IrcMessage : public QObject
{
    Q_OBJECT

private slots:
    void testFromData_data();
    void testFromData();
};

void tst_IrcMessage::testFromData_data()
{
    QTest::addColumn<QByteArray>("data");

    QTest::newRow("null") << QByteArray();
    QTest::newRow("empty") << QByteArray("");

    QTest::newRow("32 chars / 5 words") << MSG_32_5;
    QTest::newRow("64 chars / 9 words")  << MSG_64_9;
    QTest::newRow("128 chars / 19 words")  << MSG_128_19;
    QTest::newRow("256 chars / 37 words")  << MSG_256_37;
    QTest::newRow("512 chars / 75 words")  << MSG_512_75;

    QTest::newRow("32 chars / 5 words") << MSG_32_5;
    QTest::newRow("64 chars / 9 words")  << MSG_64_9;
    QTest::newRow("128 chars / 19 words")  << MSG_128_19;
    QTest::newRow("256 chars / 37 words")  << MSG_256_37;
    QTest::newRow("512 chars / 75 words")  << MSG_512_75;
}

void tst_IrcMessage::testFromData()
{
    QFETCH(QByteArray, data);

    IrcConnection connection;
    QBENCHMARK {
        IrcMessage::fromData(data, &connection);
    }
}

QTEST_MAIN(tst_IrcMessage)

#include "tst_ircmessage.moc"