text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>DOC To PDF Conversion Results</title>

<?php

// Note: If you have input files large than 200kb we highly recommend to check "async" mode example.

// Get submitted form data
$apiKey = $_POST["apiKey"]; // The authentication key (API Key). Get your own by registering at https://app.pdf.co

// 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
// * If you already have the direct PDF file link, go to the step 3.

// Create URL
$url = "https://api.pdf.co/v1/file/upload/get-presigned-url" .
    "?name=" . urlencode($_FILES["file"]["name"]) .
    "&contenttype=application/octet-stream";

// Create request
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey));
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// Execute request
$result = curl_exec($curl);

if (curl_errno($curl) == 0)
{
    $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    if ($status_code == 200)
    {
        $json = json_decode($result, true);

        if (!isset($json["error"]) || $json["error"] == false)
        {
            // Get URL to use for the file upload
            $uploadFileUrl = $json["presignedUrl"];
            // Get URL of uploaded file to use with later API calls
            $uploadedFileUrl = $json["url"];

            // 2. UPLOAD THE FILE TO CLOUD.

            $localFile = $_FILES["file"]["tmp_name"];
            $fileHandle = fopen($localFile, "r");

            curl_setopt($curl, CURLOPT_URL, $uploadFileUrl);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array("content-type: application/octet-stream"));
            curl_setopt($curl, CURLOPT_PUT, true);
            curl_setopt($curl, CURLOPT_INFILE, $fileHandle);
            curl_setopt($curl, CURLOPT_INFILESIZE, filesize($localFile));

            // Execute request
            curl_exec($curl);

            fclose($fileHandle);

            if (curl_errno($curl) == 0)
            {
                $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

                if ($status_code == 200)
                {
                    // 3. CONVERT UPLOADED DOC FILE TO PDF

                    DocToPdf($apiKey, $uploadedFileUrl, '');
                }
                else
                {
                    // Display request error
                    echo "
Status code: " . $status_code . "
";
                    echo "
" . $result . "
";
                }
            }
            else
            {
                // Display CURL error
                echo "Error: " . curl_error($curl);
            }
        }
        else
        {
            // Display service reported error
            echo "
Error: " . $json["message"] . "
";
        }
    }
    else
    {
        // Display request error
        echo "
Status code: " . $status_code . "
";
        echo "
" . $result . "
";
    }

    curl_close($curl);
}
else
{
    // Display CURL error
    echo "Error: " . curl_error($curl);
}

function DocToPdf($apiKey, $uploadedFileUrl, $pages)
{
    // Create URL
    $url = "https://api.pdf.co/v1/pdf/convert/from/doc";

    // Prepare requests params
    $parameters = array();
    $parameters["url"] = $uploadedFileUrl;
    $parameters["pages"] = $pages;

    // Create Json payload
    $data = json_encode($parameters);

    // Create request
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json"));
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    // Execute request
    $result = curl_exec($curl);

    if (curl_errno($curl) == 0)
    {
        $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if ($status_code == 200)
        {
            $json = json_decode($result, true);

            if (!isset($json["error"]) || $json["error"] == false)
            {
                $convertedFileUrl = $json["url"];
                ProtectPdf($apiKey, $convertedFileUrl);
                // // Display link to the file with conversion results
                // echo "

Conversion Result:
" . $resultFileUrl . "
";
            }
            else
            {
                // Display service reported error
                echo "
Error: " . $json["message"] . "
";
            }
        }
        else
        {
            // Display request error
            echo "
Status code: " . $status_code . "
";
            echo "
" . $result . "
";
        }
    }
    else
    {
        // Display CURL error
        echo "Error: " . curl_error($curl);
    }

    // Cleanup
    curl_close($curl);
}
function ProtectPdf($apiKey, $convertedFileUrl)
{
    // Passwords to protect PDF document
    // The owner password will be required for document modification.
    // The user password only allows to view and print the document.
    $OwnerPassword = "123456";
    $UserPassword = "654321";

    // Encryption algorithm.
    // Valid values: "RC4_40bit", "RC4_128bit", "AES_128bit", "AES_256bit".
    $EncryptionAlgorithm = "AES_128bit";

    // Allow or prohibit content extraction for accessibility needs.
    $AllowAccessibilitySupport = true;

    // Allow or prohibit assembling the document.
    $AllowAssemblyDocument = true;

    // Allow or prohibit printing PDF document.
    $AllowPrintDocument = true;

    // Allow or prohibit filling of interactive form fields (including signature fields) in PDF document.
    $AllowFillForms = true;

    // Allow or prohibit modification of PDF document.
    $AllowModifyDocument = true;

    // Allow or prohibit copying content from PDF document.
    $AllowContentExtraction = true;

    // Allow or prohibit interacting with text annotations and forms in PDF document.
    $AllowModifyAnnotations = true;

    // Allowed printing quality.
    // Valid values: "HighResolution", "LowResolution"
    $PrintQuality = "HighResolution";

    // Prepare URL for `PDF Security` API call
    $url = "https://api.pdf.co/v1/pdf/security/add";

    // Prepare requests params
    $parameters = array();
    $parameters["name"] = "result.pdf";
    $parameters["url"] = $convertedFileUrl;
    $parameters["ownerPassword"] = $OwnerPassword;
    $parameters["userPassword"] = $UserPassword;
    $parameters["encryptionAlgorithm"] = $EncryptionAlgorithm;
    $parameters["allowAccessibilitySupport"] = $AllowAccessibilitySupport;
    $parameters["allowAssemblyDocument"] = $AllowAssemblyDocument;
    $parameters["allowPrintDocument"] = $AllowPrintDocument;
    $parameters["allowFillForms"] = $AllowFillForms;
    $parameters["allowModifyDocument"] = $AllowModifyDocument;
    $parameters["allowContentExtraction"] = $AllowContentExtraction;
    $parameters["allowModifyAnnotations"] = $AllowModifyAnnotations;
    $parameters["printQuality"] = $PrintQuality;

    // Create Json payload
    $data = json_encode($parameters);

    // Create request
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json"));
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    // Execute request
    $result = curl_exec($curl);

    if (curl_errno($curl) == 0)
    {
        $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if ($status_code == 200)
        {
            $json = json_decode($result, true);

            if (!isset($json["error"]) || $json["error"] == false)
            {
                $resultFileUrl = $json["url"];

                // Display link to the result file
                echo "

Conversion Result:
" . $resultFileUrl . "
";
            }
            else
            {
                // Display service reported error
                echo "
Error: " . $json["message"] . "
";
            }
        }
        else
        {
            // Display request error
            echo "
Status code: " . $status_code . "
";
            echo "
" . $result . "
";
        }
    }
    else
    {
        // Display CURL error
        echo "Error: " . curl_error($curl);
    }

    // Cleanup
    curl_close($curl);
}

?>


text:
const clay = require('../../../dist/claygl');
const { util, helper } = require('../../common');
const path = require('path');

function createCube(material) {
    const root = new clay.Node();
    root.rotation.identity().rotateY(30 * Math.PI / 180).rotateX(30 * Math.PI / 180);

    const mesh = new clay.Mesh({
        material: material,
        geometry : new clay.geometry.Cube()
    });
    mesh.scale.set(4, 4, 4);
    root.add(mesh);

    return root;
}

describe('Integration.Material.Spec', function () {
    it('metalness and roughness', function (done) {
        const { renderer, scene, camera, canvas } = helper.createClayScene();
        const light = new clay.light.Point({
            intensity  : 0.8,
            castShadow : false,
            range: 200
        });
        light.position.set(30, -30, 30);
        light.lookAt(scene.position);
        scene.add(light);
        scene.add(new clay.light.Ambient({
            intensity: 0.2
        }));

        const material = new clay.StandardMaterial({
            metalness: 0.5,
            roughness: 0.5
        });

        const cube = createCube(material);
        scene.add(cube);

        renderer.render(scene, camera);

        util.assertWith(canvas, { fixture : path.join(__dirname, 'metalness.png') }, done);
    });

    it('maps', function (done) {
        this.timeout(10000);

        const { renderer, scene, camera, canvas } = helper.createClayScene();
        const light = new clay.light.Point({
            intensity : 0.8,
            castShadow: false,
            range: 200
        })
        light.position.set(30, -30, 30);
        light.lookAt(scene.position);
        scene.add(light);
        scene.add(new clay.light.Ambient({
            intensity: 0.4
        }));

        const promises = [ ['diffuseMap', 'basecolor'], ['normalMap', 'normal'],  ['metalnessMap', 'metalness'], ['roughnessMap', 'roughness']].map(mapInfo => {
            const tex = new clay.Texture2D({
                wrapS: clay.Texture.REPEAT,
                wratT: clay.Texture.REPEAT
            });
            return new Promise((resolve, reject) => {
                const filePath = path.join(__dirname, 'textures', 'material', 'iron-rusted4-' + mapInfo[1] + '.png');
                tex.load(filePath);
                tex.success(() => {
                    resolve({
                        define: mapInfo[0],
                        texture: tex
                    });
                });
                tex.error(reject);
            });
        });

        Promise.all(promises).then((textures) => {
            const material = new clay.StandardMaterial({
                linear: true,
                metalness: 0.5,
                roughness: 0.5,
                uvRepeat: [3, 3]
            });
            textures.forEach(t => {
                material[t.define] = t.texture;
            });
            const mesh = new clay.Mesh({
                geometry: new clay.geometry.Cube(),
                material: material
            });
            mesh.scale.set(3, 3, 3);
            // mesh.geometry.generateTangents();
            mesh.rotation.identity().rotateY(30 * Math.PI / 180).rotateX(30 * Math.PI / 180);

            const root = new clay.Node();
            root.add(mesh);
            scene.add(root);
            renderer.render(scene, camera);
            util.assertWith(canvas, { fixture: path.join(__dirname, 'maps.png'), diffOptions : { diffRatio : 0.1 } }, done);
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "ADAuthenticationResult.h"

@class ADTokenCacheItem;

/* Internally accessible methods.*/
@interface ADAuthenticationResult (Internal)

/*! Creates a result from a user or request cancellation condition, with/without correlation id. */
+ (ADAuthenticationResult*)resultFromCancellation;
+ (ADAuthenticationResult*)resultFromCancellation:(NSUUID*)correlationId;

/*! Creates an authentication result from an error condition, with/without correlation id. */
+ (ADAuthenticationResult*)resultFromError:(ADAuthenticationError*)error;
+ (ADAuthenticationResult*)resultFromError:(ADAuthenticationError*)error
                             correlationId:(NSUUID*)correlationId;

+ (ADAuthenticationResult*)resultFromParameterError:(NSString*)details;
+ (ADAuthenticationResult*)resultFromParameterError:(NSString*)details
                                      correlationId:(NSUUID*)correlationId;

/*! Creates an instance of the result from a pre-setup token cache store item */
+ (ADAuthenticationResult*)resultFromTokenCacheItem:(ADTokenCacheItem*)item
                               multiResourceRefreshToken:(BOOL)multiResourceRefreshToken
                                           correlationId:(NSUUID*)correlationId;

/*! Creates an authentication result from broker response, which can be with/without correlation id. */
+ (ADAuthenticationResult*)resultFromBrokerResponse:(NSDictionary*)response;

/*! Internal method to set the extendedLifetimeToken flag. */
- (void)setExtendedLifeTimeToken:(BOOL)extendedLifeTimeToken;
- (void)setCloudAuthority:(NSString *)cloudAuthority;

@end


text:
package org.apache.camel.component.servletlistener;

import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

/**
 *
 */
public class PropertyPlaceholderRouteTest extends ServletCamelTestSupport {

    protected String getConfiguration() {
        return "/myweb6.xml";
    }

    @Test
    public void testCamelContext() throws Exception {
        CamelContext context = getCamelContext();
        assertNotNull(context);

        assertEquals("MyCamel", context.getName());

        ProducerTemplate template = context.createProducerTemplate();

        MockEndpoint mock = context.getEndpoint("mock:result", MockEndpoint.class);
        mock.expectedBodiesReceived("Hello World");

        template.sendBody("direct:foo", "World");

        mock.assertIsSatisfied();
        template.stop();
    }

}


text:
using BusinessForms;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PalvelutoriModel.PassthroughControllers
{
    public class LoginController: PassthroughCommandController
    {
        public LoginController(BFContext context): base("login/", context)
        {

        }

        protected override Task<JObject> PerformCreate(string contextId)
        {
            return Task.FromResult(JObject.Parse("{ email: '', password: ''}"));
        }
    }
}


text:
/**
  @module ember-flexberry
*/

import Ember from 'ember';

/**
  Edit forms routes mixin which handles save/delete operations indication.

  @class EditFormRouteOperationsIndicationMixin
*/
export default Ember.Mixin.create({
  /**
    Flag: indicates whether it's transition from new route or not.

    @property recordAdded.
    @type Boolean
    @default false
   */
  recordAdded: false,

  /**
    This hook is the first of the route entry validation hooks called when an attempt is made to transition into a route or one of its children.
    [More info](http://emberjs.com/api/classes/Ember.Route.html#method_beforeModel).

    @method beforeModel
    @param {Transition} transition
    @return {Promise}
  */
  beforeModel(transition) {
    let result = this._super(...arguments);

    if (!(result instanceof Ember.RSVP.Promise)) {
      result = Ember.RSVP.resolve();
    }

    return new Ember.RSVP.Promise((resolve, reject) => {
      result.then((parentResult) => {
        this.set('recordAdded', transition.queryParams.recordAdded || false);
        resolve(parentResult);
      }).catch((reason) => {
        reject(reason);
      });
    });
  },

  /**
    A hook you can use to setup the controller for the current route.
    [More info](http://emberjs.com/api/classes/Ember.Route.html#method_setupController).

    @method setupController
    @param {Controller} controller
  */
  setupController(controller) {
    this._super(...arguments);

    let recordAdded = this.get('recordAdded');
    controller.set('showFormSuccessMessage', recordAdded);
    if (recordAdded) {
      controller.set('latestOperationType', 'save');
    }
  },

  /**
    A hook you can use to reset controller values either when the model changes or the route is exiting.
    [More info](http://emberjs.com/api/classes/Ember.Route.html#method_resetController).

    @method resetController
    @param {Ember.Controller} controller
    @param {Boolean} isExisting
    @param {Object} transition
   */
  resetController: function(controller, isExisting, transition) {
    this._super.apply(this, arguments);

    controller.set('showFormSuccessMessage', false);
    controller.set('showFormErrorMessage', false);
  }
});


text:
/*
 * SolverLamg.h
 *
 *  Created on: 12.01.2015
 *      Author: Michael
 */

#ifndef SOLVERLAMG_H_
#define SOLVERLAMG_H_

#include "LevelHierarchy.h"
#include "../Smoother.h"
#include "../../algebraic/DenseMatrix.h"

namespace NetworKit {

/**
 * Status parameters of the solver.
 */
struct LAMGSolverStatus {
	// in
	count maxIters = std::numeric_limits<count>::max(); // maximum number of iterations
	count maxConvergenceTime = std::numeric_limits<count>::max(); // maximum time in milliseconds spent to solve the system
	double desiredResidualReduction = 1e-8; // desired reduction of the initial residual (finalResidual <= desiredResReduction * initialResidual)
	count numPreSmoothIters = 1; // number of pre smoothing iterations
	count numPostSmoothIters = 2; // number of post smoothing iterations

	// out
	count numIters; // number of iterations needed during solve phase
	double residual; // absolute final residual
	bool converged; // flag of conversion status
	std::vector<double> residualHistory; // history of absolute residuals
};

/**
 * @ingroup numerics
 * Implements the solve phase of LAMG (Lean Algebraic Multigrid by Livne et al.).
 */
template<class Matrix>
class SolverLamg {
private:
	LevelHierarchy<Matrix> &hierarchy;
	const Smoother<Matrix> &smoother;

	// data structures for iterate recombination
	std::vector<std::vector<Vector>> history;
	std::vector<std::vector<Vector>> rHistory;
	std::vector<index> latestIterate;
	std::vector<count> numActiveIterates;

	// bStages for Elimination Levels
	std::vector<std::vector<Vector>> bStages;

	void solveCycle(Vector& x, const Vector& b, int finest, LAMGSolverStatus& status);
	void cycle(Vector& x, const Vector& b, int finest, int coarsest, std::vector<count>& numVisits, std::vector<Vector>& X, std::vector<Vector>& B, const LAMGSolverStatus& status);
	void multigridCycle(index level, Vector& xf, const Vector& bf);
	void saveIterate(index level, const Vector& x, const Vector& r);
	void clearHistory(index level);
	void minRes(index level, Vector& x, const Vector& r);

public:
	/**
	 * Constructs a new solver instance for the specified @a hierarchy. The @a smoother will be used for relaxing and
	 * solving the coarser solutions.
	 * @param hierarchy Reference to the LevelHierarchy constructed by MultiLevelSetup.
	 * @param smoother Reference to a smoother.
	 */
	SolverLamg(LevelHierarchy<Matrix>& hierarchy, const Smoother<Matrix>& smoother) : hierarchy(hierarchy), smoother(smoother), bStages(hierarchy.size(), std::vector<Vector>()) {}

	SolverLamg (const SolverLamg<Matrix>& other) = default;

	SolverLamg (SolverLamg<Matrix>&& other) = default;

	virtual ~SolverLamg() = default;

	SolverLamg& operator=(SolverLamg<Matrix>&& other) = default;

	SolverLamg& operator=(const SolverLamg<Matrix>& other) = default;

	/**
	 * Solves the system A*x = b for the given initial @a x and right-hand side @a b. More parameters can be specified
	 * in @a status and additional output is also stored in @a status. After the solver finished, the approximate
	 * solution is stored in @a x.
	 * @param x[out] Reference to the initial guess to the solution and the approximation after the solver finished.
	 * @param b The right-hand side vector.
	 * @param status Reference to an LAMGSolverStatus.
	 */
	void solve(Vector& x, const Vector& b, LAMGSolverStatus& status);
};

template<class Matrix>
void SolverLamg<Matrix>::solve(Vector& x, const Vector& b, LAMGSolverStatus& status) {
	bStages = std::vector<std::vector<Vector>>(hierarchy.size(), std::vector<Vector>());
	if (hierarchy.size() >= 2) {
		Vector bc = b;
		Vector xc = x;
		int finest = 0;

		if (hierarchy.getType(1) == ELIMINATION) {
			hierarchy.at(1).restrict(b, bc, bStages[1]);
			if (hierarchy.at(1).getLaplacian().numberOfRows() == 1) {
				x = 0.0;
				return;
			} else {
				hierarchy.at(1).coarseType(x, xc);
				finest = 1;
			}
		}
		solveCycle(xc, bc, finest, status);

		if (finest == 1) { // interpolate from finest == ELIMINATION level back to actual finest level
			hierarchy.at(1).interpolate(xc, x, bStages[1]);
		} else {
			x = xc;
		}
	} else {
		solveCycle(x, b, 0, status);
	}

	double residual = (b - hierarchy.at(0).getLaplacian() * x).length();
	status.residual = residual;
}

template<class Matrix>
void SolverLamg<Matrix>::solveCycle(Vector& x, const Vector& b, int finest, LAMGSolverStatus& status) {
	Aux::Timer timer;
	timer.start();

	// data structures for iterate recombination
	history = std::vector<std::vector<Vector>>(hierarchy.size());
	rHistory = std::vector<std::vector<Vector>>(hierarchy.size());
	latestIterate = std::vector<index>(hierarchy.size(), 0);
	numActiveIterates = std::vector<count>(hierarchy.size(), 0);
	int coarsest = hierarchy.size() - 1;
	std::vector<count> numVisits(coarsest);
	std::vector<Vector> X(hierarchy.size());
	std::vector<Vector> B(hierarchy.size());

	for (index i = 0; i < hierarchy.size(); ++i) {
		history[i] = std::vector<Vector>(MAX_COMBINED_ITERATES, Vector(hierarchy.at(i).getNumberOfNodes()));
		rHistory[i] = std::vector<Vector>(MAX_COMBINED_ITERATES, Vector(hierarchy.at(i).getNumberOfNodes()));
	}

	Vector r = b - hierarchy.at(finest).getLaplacian() * x;
	double residual = r.length();
	double finalResidual = residual * status.desiredResidualReduction;
	double bestResidual = std::numeric_limits<double>::max();

	count iterations = 0;
	status.residualHistory.emplace_back(residual);
	count noResReduction = 0;
	while (residual > finalResidual && noResReduction < 5 && iterations < status.maxIters && timer.elapsedMilliseconds() <= status.maxConvergenceTime ) {
		cycle(x, b, finest, coarsest, numVisits, X, B, status);
		r = b - hierarchy.at(finest).getLaplacian() * x;
		residual = r.length();
		status.residualHistory.emplace_back(residual);
		if (residual < bestResidual) {
			noResReduction = 0;
			bestResidual = residual;
		} else {
			++noResReduction;
		}
		iterations++;
	}

	timer.stop();

	status.numIters = iterations;
	status.residual = r.length();
	status.converged = r.length() <= finalResidual;
}

template<class Matrix>
void SolverLamg<Matrix>::cycle(Vector& x, const Vector& b, int finest, int coarsest, std::vector<count>& numVisits, std::vector<Vector>& X, std::vector<Vector>& B, const LAMGSolverStatus& status) {
	std::fill(numVisits.begin(), numVisits.end(), 0);
	X[finest] = x;
	B[finest] = b;

	int currLvl = finest;
	int nextLvl = finest;
	double maxVisits = 0.0;

	saveIterate(currLvl, X[currLvl], B[currLvl] - hierarchy.at(currLvl).getLaplacian() * X[currLvl]);
	while (true) {
		if (currLvl == coarsest) {
			nextLvl = currLvl - 1;
			if (currLvl == finest) { // finest level
				X[currLvl] = smoother.relax(hierarchy.at(currLvl).getLaplacian(), B[currLvl], X[currLvl], status.numPreSmoothIters);
			} else {
				Vector bCoarse(B[currLvl].getDimension()+1, 0.0);
				for (index i = 0; i < B[currLvl].getDimension(); ++i) {
					bCoarse[i] = B[currLvl][i];
				}

				Vector xCoarse = DenseMatrix::LUSolve(hierarchy.getCoarseMatrix(), bCoarse);
				for (index i = 0; i < X[currLvl].getDimension(); ++i) {
					X[currLvl][i] = xCoarse[i];
				}
			}
		} else {
			if (currLvl == finest) {
				maxVisits = 1.0;
			} else {
				maxVisits = hierarchy.cycleIndex(currLvl) * numVisits[currLvl-1];
			}

			if (numVisits[currLvl] < maxVisits) {
				nextLvl = currLvl + 1;
			} else {
				nextLvl = currLvl - 1;
			}
		}

		if (nextLvl < finest) break;

		if (nextLvl > currLvl) {  // preProcess
			numVisits[currLvl]++;

			if (hierarchy.getType(nextLvl) != ELIMINATION) {
				X[currLvl] = smoother.relax(hierarchy.at(currLvl).getLaplacian(), B[currLvl], X[currLvl], status.numPreSmoothIters);
			}

			if (hierarchy.getType(nextLvl) == ELIMINATION) {
				hierarchy.at(nextLvl).restrict(B[currLvl], B[nextLvl], bStages[nextLvl]);
			} else {
				hierarchy.at(nextLvl).restrict(B[currLvl] - hierarchy.at(currLvl).getLaplacian() * X[currLvl], B[nextLvl]);
			}

			hierarchy.at(nextLvl).coarseType(X[currLvl], X[nextLvl]);

			clearHistory(nextLvl);
		} else { // postProcess
			if (currLvl == coarsest || hierarchy.getType(currLvl+1) != ELIMINATION) {
				minRes(currLvl, X[currLvl], B[currLvl] - hierarchy.at(currLvl).getLaplacian() * X[currLvl]);
			}

			if (nextLvl > finest) {
				saveIterate(nextLvl, X[nextLvl], B[nextLvl] - hierarchy.at(nextLvl).getLaplacian() * X[nextLvl]);
			}

			if (hierarchy.getType(currLvl) == ELIMINATION) {
				hierarchy.at(currLvl).interpolate(X[currLvl], X[nextLvl], bStages[currLvl]);
			} else {
				Vector xf = X[nextLvl];
				hierarchy.at(currLvl).interpolate(X[currLvl], xf);
				X[nextLvl] += xf;
			}

			if (hierarchy.getType(currLvl) != ELIMINATION) {
				X[nextLvl] = smoother.relax(hierarchy.at(nextLvl).getLaplacian(), B[nextLvl], X[nextLvl], status.numPostSmoothIters);
			}

		}

		currLvl = nextLvl;
	} // while

	// post-cycle finest
	if ((int64_t) hierarchy.size() > finest + 1 && hierarchy.getType(finest+1) != ELIMINATION) { // do an iterate recombination on calculated solutions
		minRes(finest, X[finest], B[finest] - hierarchy.at(finest).getLaplacian() * X[finest]);
	}

	X[finest] -= X[finest].mean();
	x = X[finest];
}

template<class Matrix>
void SolverLamg<Matrix>::saveIterate(index level, const Vector& x, const Vector& r) {
	// update latest pointer
	index i = latestIterate[level];
	latestIterate[level] = (i+1) % MAX_COMBINED_ITERATES;

	// update numIterates
	if (numActiveIterates[level] < MAX_COMBINED_ITERATES) {
		numActiveIterates[level]++;
	}

	// update history array
	history[level][i] = x;
	rHistory[level][i] = r;
}

template<class Matrix>
void SolverLamg<Matrix>::clearHistory(index level) {
	latestIterate[level] = 0;
	numActiveIterates[level] = 0;
}

template<class Matrix>
void SolverLamg<Matrix>::minRes(index level, Vector& x, const Vector& r) {
	if (numActiveIterates[level] > 0) {
		count n = numActiveIterates[level];

		std::vector<index> ARowIdx(r.getDimension()+1);
		std::vector<index> ERowIdx(r.getDimension()+1);

#pragma omp parallel for
		for (index i = 0; i < r.getDimension(); ++i) {
			for (index k = 0; k < n; ++k) {
				double AEvalue = r[i] - rHistory[level][k][i];
				if (std::fabs(AEvalue) > 1e-25) {
					++ARowIdx[i+1];
				}

				double Eval = history[level][k][i] - x[i];
				if (std::fabs(Eval) > 1e-25) {
					++ERowIdx[i+1];
				}
			}
		}

		for (index i = 0; i < r.getDimension(); ++i) {
			ARowIdx[i+1] += ARowIdx[i];
			ERowIdx[i+1] += ERowIdx[i];
		}

		std::vector<index> AColumnIdx(ARowIdx[r.getDimension()]);
		std::vector<double> ANonZeros(ARowIdx[r.getDimension()]);

		std::vector<index> EColumnIdx(ERowIdx[r.getDimension()]);
		std::vector<double> ENonZeros(ERowIdx[r.getDimension()]);

#pragma omp parallel for
		for (index i = 0; i < r.getDimension(); ++i) {
			for (index k = 0, aIdx = ARowIdx[i], eIdx = ERowIdx[i]; k < n; ++k) {
				double AEvalue = r[i] - rHistory[level][k][i];
				if (std::fabs(AEvalue) > 1e-25) {
					AColumnIdx[aIdx] = k;
					ANonZeros[aIdx] = AEvalue;
					++aIdx;
				}

				double Eval = history[level][k][i] - x[i];
				if (std::fabs(Eval) > 1e-25) {
					EColumnIdx[eIdx] = k;
					ENonZeros[eIdx] = Eval;
					++eIdx;
				}
			}
		}

		CSRMatrix AE(r.getDimension(), n, ARowIdx, AColumnIdx, ANonZeros, 0.0, true);
		CSRMatrix E(r.getDimension(), n, ERowIdx, EColumnIdx, ENonZeros, 0.0, true);

		Vector alpha = smoother.relax(CSRMatrix::mTmMultiply(AE, AE), CSRMatrix::mTvMultiply(AE, r), Vector(n, 0.0), 10);
		x += E * alpha;
	}

}

} /* namespace NetworKit */

#endif /* SOLVERLAMG_H_ */


text:
using System;

using Orion.Shared.Models;

namespace Orion.Shared.Absorb.Objects
{
    public class StatusBase : BindableBase2
    {
        /// <summary>
        ///     ステータス ID (numeric)
        /// </summary>
        public long Id { get; protected set; }

        /// <summary>
        ///     投稿日時
        /// </summary>
        public DateTime CreatedAt { get; protected set; }

        /// <summary>
        ///     投稿ユーザー (User)
        /// </summary>
        public User User { get; protected set; }

        /// <summary>
        ///     型
        /// </summary>
        public string Type { get; protected set; }

        /// <summary>
        ///     投稿元プロバイダ
        /// </summary>
        public string Provider { get; protected set; }

        /// <summary>
        ///     true の場合、全ての分岐に対して通知を行います。
        /// </summary>
        internal bool IsBroadcastStatus { get; set; }

        /// <summary>
        ///     通知時に、 ID の重複検査を無視します。
        /// </summary>
        internal bool IgnoreIdDuplication { get; set; }
    }
}


text:
layout: default
description: Single Instance
---
# Single Instance

Running a single instance of ArangoDB is the most simple way to get started.
It means to run the ArangoDB Server binary `arangod` stand-alone, without
replication, without failover opportunity, and not as cluster together with
other nodes.

You may run multiple processes of `arangod` side-by-side on the same machine as
single instances, as long as they are configured for different ports and data
folders. The official installers may not support multiple installations
side-by-side, but you can get archive packages and unpack them manually.

The provided ArangoDB packages run as single instances out of the box.

Unlike other setups, like the *Active Failover*, *Cluster*, or *Multiple Datacenters*,
which require some specific procedure to be started once the ArangoDB package
has been installed, deploying a single-instance is straightforward.

Depending on your operating system, after the installation, the ArangoDB Server
might be already up and running. *Start*, *stop* and *restart* operations can
be handled directly by using your *System and Service Manager*.

The following are two additional ways that can be used to start the stand-alone
instance:

- Using the [ArangoDB Starter tool](deployment-single-instance-using-the-starter.html), or
- [manually](deployment-single-instance-manual-start.html).


text:
<?php
namespace ZF2DoctrineTools\Initializer;
use Zend\ServiceManager\InitializerInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZF2DoctrineTools\Persistence\EntityManagerAwareInterface;
use ZF2DoctrineTools\Translator\TranslatorAwareInterface;

/**
 * @author Laurynas Tretjakovas(n3ziniuka5) <laurynas.tretjakovas@gmail.com>
 */
class ViewHelperInitializer implements InitializerInterface
{
    public function initialize($instance, ServiceLocatorInterface $helperPluginManager)
    {
        $serviceManager = $helperPluginManager->getServiceLocator();
        if ($instance instanceof TranslatorAwareInterface) {
            $translator = $serviceManager->get('translator');
            $instance->setTranslator($translator);
        }
        if ($instance instanceof EntityManagerAwareInterface) {
            $entityManager = $serviceManager->get('Doctrine\ORM\EntityManager');
            $instance->setEntityManager($entityManager);
        }
    }
}


text:
package com.iluwatar.command;

import java.util.Deque;
import java.util.LinkedList;

/**
 *
 * Wizard is the invoker of the commands
 *
 */
public class Wizard {

  private Deque<Command> undoStack = new LinkedList<>();
  private Deque<Command> redoStack = new LinkedList<>();

  public Wizard() {}

  public void castSpell(Command command, Target target) {
    System.out.println(this + " casts " + command + " at " + target);
    command.execute(target);
    undoStack.offerLast(command);
  }

  public void undoLastSpell() {
    if (!undoStack.isEmpty()) {
      Command previousSpell = undoStack.pollLast();
      redoStack.offerLast(previousSpell);
      System.out.println(this + " undoes " + previousSpell);
      previousSpell.undo();
    }
  }

  public void redoLastSpell() {
    if (!redoStack.isEmpty()) {
      Command previousSpell = redoStack.pollLast();
      undoStack.offerLast(previousSpell);
      System.out.println(this + " redoes " + previousSpell);
      previousSpell.redo();
    }
  }

  @Override
  public String toString() {
    return "Wizard";
  }
}


text:
.. -*- coding: utf-8 -*-
.. URL: https://docs.docker.com/engine/reference/commandline/swarm_init/
.. SOURCE: https://github.com/docker/docker/blob/master/docs/reference/commandline/swarm_init.md
   doc version: 1.12
      https://github.com/docker/docker/commits/master/docs/reference/commandline/swarm_init.md
.. check date: 2016/06/16
.. Commits on Jun 14, 2016 9acf97b72a4d5ff7b1bcad36fb19b53775f01596
.. -------------------------------------------------------------------

.. Warning: this command is part of the Swarm management feature introduced in Docker 1.12, and might be subject to non backward-compatible changes.

.. warning::

  このコマンドは Docker 1.12 で導入された Swarm 管理機能の一部です。それと、変更は下位互換性を考慮していない可能性があります。

.. swarm init

=======================================
swarm init
=======================================

.. code-block:: bash

   使い方:  docker swarm init [オプション]

   Swarm を初期化

   オプション:
         --auto-accept value   受け入れ可能なポリシー (デフォルト [worker,manager])
         --force-new-cluster   現状で、強制的に新しいクラスタを作成
         --help                使い方の表示
         --listen-addr value   リッスンするアドレス (デフォルト 0.0.0.0:2377)
         --secret string       ノードがクラスタ参加時に必要なシークレット値を設定

.. Initialize a Swarm cluster. The docker engine targeted by this command becomes a manager in the newly created one node Swarm cluster.

Swarm クラスタを初期化します。このコマンドを実行する Docker Engine は、直近に作成した Swarm クラスタ上のマネージャ(manager)になります。

.. code-block:: bash

   $ docker swarm init --listen-addr 192.168.99.121:2377
   Initializing a new swarm
   $ docker node ls
   ID              NAME          STATUS  AVAILABILITY/MEMBERSHIP  MANAGER STATUS  LEADER
   3l1f6uzcuoa3 *  swarm-master  READY   ACTIVE                   REACHABLE       Yes

``--auto-accept`` 値
------------------------------

.. This flag controls node acceptance into the cluster. By default, both worker and manager nodes are auto accepted by the cluster. This can be changed by specifing what kinds of nodes can be auto-accepted into the cluster. If auto-accept is not turned on, then node accept can be used to explicitly accept a node into the cluster.

このフラグはクラスタに受け入れるノードを制御します。デフォルトではクラスタが自動的にノードを受け入れる ``worker`` と ``manager`` ノードです。クラスタでどのようなノードを自動的に受け入れるかは、変更可能です。自動受け入れを有効にした場合は、それ以外のノードをクラスタに追加するために :doc:`node accept <node_accept>` を使います。

.. For example, the following initializes a cluster with auto-acceptance of workers, but not managers

次の例は、 worker を自動受け入れしますが manager は受け入れないようクラスタを初期化します。

.. code-block:: bash

   $ docker swarm init --listen-addr 192.168.99.121:2377 --auto-accept worker
   Initializing a new swarm

``--force-new-cluster``
------------------------------

.. This flag forces an existing node that was part of a quorum that was lost to restart as a single node Manager without losing its data

このフラグは既存のノードでクォーラムを強制的に構成します。1つのノード・マネージャがデータを持っていたとしても、再構成によってデータを失います。

``--listen-addr value``
------------------------------

.. The node listens for inbound Swarm manager traffic on this IP:PORT

Swarm マネージャからのインバウンド通信をリッスンするための、ノードの IP:PORT を指定します。

``--secret string``
--------------------

.. Secret value needed to accept nodes into the Swarm

ノードが Swarm に受け入れられるために必要なシークレット値です。

関連情報
----------

* :doc:`swarm_join`
* :doc:`swarm_leave`
* :doc:`swarm_update`

.. seealso::

   swarm init
      https://docs.docker.com/engine/reference/commandline/swarm_init/


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Genesis.Net
{
    public class TransactionTypes
    {
        internal static readonly Lazy<Dictionary<String, TransactionTypes>> TransactionTypesByName = new Lazy<Dictionary<string, TransactionTypes>>(() =>
        {
            return typeof(TransactionTypes)
                .GetFields(BindingFlags.Public | BindingFlags.Static)
                .ToDictionary(f => ((TransactionTypes)f.GetValue(null)).Name, f => (TransactionTypes)f.GetValue(null));
        });

        public static readonly TransactionTypes Authorize = new TransactionTypes(1, "authorize");

        public static readonly TransactionTypes Authorize3d = new TransactionTypes(2, "authorize3d");

        public static readonly TransactionTypes Capture = new TransactionTypes(3, "capture");

        public static readonly TransactionTypes Sale = new TransactionTypes(4, "sale");

        public static readonly TransactionTypes Sale3d = new TransactionTypes(5, "sale3d");

        public static readonly TransactionTypes InitRecurringSale = new TransactionTypes(6, "init_recurring_sale");

        public static readonly TransactionTypes InitRecurringSale3d = new TransactionTypes(7, "init_recurring_sale3d");

        public static readonly TransactionTypes RecurringSale = new TransactionTypes(8, "recurring_sale");

        public static readonly TransactionTypes Refund = new TransactionTypes(9, "refund");

        public static readonly TransactionTypes Void = new TransactionTypes(10, "void");

        public static readonly TransactionTypes Credit = new TransactionTypes(11, "credit");

        public static readonly TransactionTypes Payout = new TransactionTypes(12, "payout");

        public static readonly TransactionTypes AccountVerification = new TransactionTypes(13, "account_verification");

        public static readonly TransactionTypes Avs = new TransactionTypes(14, "avs");

        public static readonly TransactionTypes EzeeWallet = new TransactionTypes(15, "ezeewallet");

        public static readonly TransactionTypes PayByVoucher = new TransactionTypes(16, "paybyvoucher");

        public static readonly TransactionTypes CashU = new TransactionTypes(17, "cashu");

        public static readonly TransactionTypes PaySafeCard = new TransactionTypes(18, "paysafecard");

        public static readonly TransactionTypes Sofort = new TransactionTypes(19, "sofort");

        public static readonly TransactionTypes SofortiDeal = new TransactionTypes(20, "sofort_ideal");

        public static readonly TransactionTypes Ppro = new TransactionTypes(21, "ppro");

        public static readonly TransactionTypes GooglePay = new TransactionTypes(22, "google_pay");

        public static readonly TransactionTypes ApplePay = new TransactionTypes(23, "apple_pay");

        public readonly short Value;
        public readonly string Name;

        private TransactionTypes(short value, string name)
        {
            Value = value;
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }

        public override bool Equals(object obj)
        {
            TransactionTypes other = obj as TransactionTypes;
            if (other != null)
            {
                return Value.Equals(other.Value);
            }

            return false;
        }

        public override int GetHashCode()
        {
            return Value.GetHashCode();
        }
    }
}


text:
[JGrid]() - jQuery based Grid library
==================================================

(Requires jQuery and Mustache)

JGrid uses a *Model*-*Store*-*Grid* approach for data-binding.

Usage
=====

Create a new **model** instance.`

	var model = new JGrid.Model([{
		"name":"location"
	},{
		"name":"age"
	}
	]);

Create a **store** instance and bind the model to this store.

	var store = new JGrid.Store(model,{
			"proxy":{
				"url":{endpoint url of REST service},
				"type":"AJAX",
				"root":{entrypoint to search for data,defaults to data},
				"record":{the entry point to search for records/rows}
			}
		});

Create a **grid** instance and bind the store. Also pass in the columns config and target (required)

	var grid = new JGrid.Grid({
			"store":store,
			"columns":[{
				"header":"Location Name",
				"dataIndex":"location"
			},{
				"header":"Age",
				"dataIndex":"age"
			}],
			"target":"grid-container",
		});

**Sample Data**

	{
		"data": {
			"rows": [{
				"age": 20,
				"location": "India"
			}, {
				"age": 21,
				"location": "Australia"
			}, {
				"age": 30,
				"location": "England"
			}, {
				"age": 15,
				"location": "USA"
			}, {
				"age": 53,
				"location": "South Africa"
			}, {
				"age": 20,
				"location": "New Zealand"
			}]
		}
	}

#API

## Model

>>**Configuration** Configuration options for each Model instance

	new Model(field,mappings)

*field* - An array of field configurations.

	{
		"name":{@required,the name of the field},
		"type":{the datatype of the field - number/float/currency/string}
		"convert":{optional function that will be called before storing the raw value of the field}
	}

*field* -> *convert* - The raw value of the field is passed in. Should return a valid value.
			Useful for data-formatting.

	"convert":function(value){
		return value.toUpperCase();
	}

*mappings* - Used for specifying has-many associations for each record. More on this later.

>>**Methods** Methods available on a Model instance

*get* - A Model in turn creates a Record object. The 'get' method returns the value of the field passed in.

	recordInstance.get(fieldName);

>>**Events** There are no events associated with a Model instance.

## Store
>>**Configuration** Configuration options for creating a Store

	new Store(model,options)

*model* - A model instance

*options* -  Additional options for configuring a store

*options* -> *proxy* - The proxy object is responsible for creating a connection between the store and the REST endpoint.

	{
		"proxy":{
			"url":{end point URL},
			"type":{AJAX/memory},
			"root":{Optional root config},
			"record":{Optional record config},
			"data":{data object. Required when using a memory proxy}
		}
	}

>>**Properties** Properties of a store instance

*count (int)* - The number of records present in a store.
*isStoreLoading (boolean)* - Indicates if the store is currently loading.
*isStoreLoaded (boolean)* - Indicates that the store has finished loading.
*data (array)* - An array of records, present in the store.
*rawData (object)* - The raw data received from the server.

>>**Methods** Methods available on a store instance

*add* - Used to add a row to the store. Only one row can be added at a time. The recordObject should be a normal JavaScript object with field names and values

	storeInstance.add(Object recordObj);

*addAll* - Used to add multiple records to a store. Records is an array of JavaScript objects

	storeInstance.add(Array records);

*each* - Used to iterate through the records in a store.

	storeInstance.add(Function function(int idx,Record record){...});

*find* - Used to find a record within a store. Returns null if no match is found.

	storeInstance.find(string fieldName,string value,[boolean isCaseSensitive,boolean anyMatch]);

*findById* - Used to find a record within a store using the record id. Returns null if no match is found.

	storeInstance.find(string id);

*getAt* - Returns the object at a given index. Returns null if no match is found.

	storeInstance.getAt(int idx);

*insertAt* - Used to add a row to the store at a given index. Only one row can be added at a time.

	storeInstance.insertAt(int idx, Object recordObj);

*load* -  Used to load/reload the store by making a new request to the server, optionally providing a new url and params

	storeInstance.load([string url, Object params]);

*on* - Add an event listener on the store instance. See the events section for more information.

	storeInstance.on(string eventName, Function callback, [Object scope]);

*off* - Remove an event listener on the store instance. See the events section for more information.

	storeInstance.on(string eventName, [Function callback]);

*remove* - Used to remove a row to the store at a given index. The first record for which the callback returns true is removed.

	storeInstance.remove(Function function(record){});

*removeAt* - Used to remove a row from the store at a given index. Only one row can be removed at a time.

	storeInstance.removeAt(int idx);

*removeAll* - Used to remove all rows from the store.

	storeInstance.removeAll();

*sort* - Used to sort the store

	storeInstance.sort(string fieldName, string direction);

>>**Events** Events available on a store instance

*load* - The load event is triggered once an AJAX request to the server succeeds.

	function(Store storeInstance, Array records);

## Grid
>>**Configuration** Configuration options for creating a Grid

	new Grid(options);

*options* -  Additional options for configuring a store

*options* -> *store* - A store instance or a store configuration object.

*options* -> *columns* - An array of column configurations.

	'columns': [{
			'header': '{column name}',
			'dataIndex': '{key name that links the column to a field in the store/model}',
			'renderer':{function(val){..} - An optional function that will be called before rendering the column as markup.}
		}, {
			...
		}]
*options* -> *templates* - Optional configuration object specifying the Mustache templates to be used. Can be used to customise the tables.

*options* -> *target* - The id or the DOM node, in which the grid is to be rendered.

*options* -> *className* - Optional classes to be added on to the grid. Allows adding custom styles.

*options* -> *id* - Optional id to be added on to the grid.

>>**Properties** Properties of a grid instance

*el* - The element in which the grid is rendered.

*gridEl* - The table element behind the grid.

>>**Methods** Methods available on a store instance

*load* - Used to update the grid by calling the underlying store's load method.

	grid.load([string url,Object params]);

*destroy* - Used to destroy the grid

	grid.destroy();

*sort* - Used to sort the grid.

	grid.sort(string fieldName, string direction);

*filter* - Used to filter the grid based on the field and value

	grid.filter(string fieldName, string fieldValue);

*on* - Add an event listener on the grid instance. See the events section for more information.

	grid.on(string eventName, Function callback, [Object scope]);

*off* - Remove an event listener on the grid instance. See the events section for more information.

	grid.on(string eventName, [Function callback]);

>>**Events** Events available on a store instance

*beforerender* - This event is fired when the grid's markup is generated, but before it is rendered. Return false from to prevent the grid from rendering.

	function(Grid grid, DOMNode el, DocumentFragment table, DocumentFragment tableBody);

*afterrender* - This event is fired after the grid is rendered.

	function(Grid grid, DOMNode el, DOMNode table);

*rowclick* - This event is fired when the a row is clicked.

	function(Grid grid, Record record, DOMNode tdElement, DOMNode trElement);


text:
package access

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	routing "github.com/go-ozzo/ozzo-routing/v2"
)

// LogFunc logs a message using the given format and optional arguments.
// The usage of format and arguments is similar to that for fmt.Printf().
// LogFunc should be thread safe.
type LogFunc func(format string, a ...interface{})

// LogWriterFunc takes in the request and responseWriter objects as well
// as a float64 containing the elapsed time since the request first passed
// through this middleware and does whatever log writing it wants with that
// information.
// LogWriterFunc should be thread safe.
type LogWriterFunc func(req *http.Request, res *LogResponseWriter, elapsed float64)

// CustomLogger returns a handler that calls the LogWriterFunc passed to it for every request.
// The LogWriterFunc is provided with the http.Request and LogResponseWriter objects for the
// request, as well as the elapsed time since the request first came through the middleware.
// LogWriterFunc can then do whatever logging it needs to do.
//
//     import (
//         "log"
//         "github.com/go-ozzo/ozzo-routing/v2"
//         "github.com/go-ozzo/ozzo-routing/v2/access"
//         "net/http"
//     )
//
//     func myCustomLogger(req http.Context, res access.LogResponseWriter, elapsed int64) {
//         // Do something with the request, response, and elapsed time data here
//     }
//     r := routing.New()
//     r.Use(access.CustomLogger(myCustomLogger))
func CustomLogger(loggerFunc LogWriterFunc) routing.Handler {
	return func(c *routing.Context) error {
		startTime := time.Now()

		req := c.Request
		rw := &LogResponseWriter{c.Response, http.StatusOK, 0}
		c.Response = rw

		err := c.Next()

		elapsed := float64(time.Now().Sub(startTime).Nanoseconds()) / 1e6
		loggerFunc(req, rw, elapsed)

		return err
	}

}

// Logger returns a handler that logs a message for every request.
// The access log messages contain information including client IPs, time used to serve each request, request line,
// response status and size.
//
//     import (
//         "log"
//         "github.com/go-ozzo/ozzo-routing/v2"
//         "github.com/go-ozzo/ozzo-routing/v2/access"
//     )
//
//     r := routing.New()
//     r.Use(access.Logger(log.Printf))
func Logger(log LogFunc) routing.Handler {
	var logger = func(req *http.Request, rw *LogResponseWriter, elapsed float64) {
		clientIP := GetClientIP(req)
		requestLine := fmt.Sprintf("%s %s %s", req.Method, req.URL.String(), req.Proto)
		log(`[%s] [%.3fms] %s %d %d`, clientIP, elapsed, requestLine, rw.Status, rw.BytesWritten)

	}
	return CustomLogger(logger)
}

// LogResponseWriter wraps http.ResponseWriter in order to capture HTTP status and response length information.
type LogResponseWriter struct {
	http.ResponseWriter
	Status       int
	BytesWritten int64
}

func (r *LogResponseWriter) Write(p []byte) (int, error) {
	written, err := r.ResponseWriter.Write(p)
	r.BytesWritten += int64(written)
	return written, err
}

// WriteHeader records the response status and then writes HTTP headers.
func (r *LogResponseWriter) WriteHeader(status int) {
	r.Status = status
	r.ResponseWriter.WriteHeader(status)
}

// GetClientIP returns the client IP address from the given HTTP request.
func GetClientIP(req *http.Request) string {
	ip := req.Header.Get("X-Real-IP")
	if ip == "" {
		ip = req.Header.Get("X-Forwarded-For")
		if ip == "" {
			ip = req.RemoteAddr
		}
	}
	if colon := strings.LastIndex(ip, ":"); colon != -1 {
		ip = ip[:colon]
	}
	return ip
}


text:
/* eslint-disable no-void */
/* eslint-disable @lwc/lwc/no-async-operation */
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import UtilDescribe from './utilDescribe';
import unknownErrorLabel from '@salesforce/label/c.commonUnknownError';
import commonLabelNone from '@salesforce/label/c.stgLabelNone';
const FUNCTION = 'function';
const OBJECT = 'object';

/*******************************************************************************
 * @description 'Debouncifies' any function.
 *
 * @param {object} anyFunction: Function to be debounced.
 * @param {number} wait: Time to wait by in milliseconds.
 * @returns {function<Promise>} A debounced version of the function originally
 * passed to debouncify
 */
const debouncify = (anyFunction, wait) => {
    let timeoutId;

    return (...argsFromLastCall) => {
        window.clearTimeout(timeoutId);

        return new Promise(resolve => {
            timeoutId = window.setTimeout(() => {
                resolve(anyFunction(...argsFromLastCall));
            }, wait);
        });
    };
};

/*******************************************************************************
 * @description Finds an item in an array by a property.
 *
 * @param {list} array: List of items.
 * @param {string} property: Property to find by.
 * @param {string} value: Value of property to check against.
 *
 * @return {Integer}: Index of the item from provided array.
 */
const findIndexByProperty = (array, property, value) => {
    return array.findIndex(element => element[property] === value);
};

/*******************************************************************************
 * @description Collects all query parameters in the URL and returns them as a
 * map.
 *
 * @return {object} params: Map of query parameters.
 */
const getQueryParameters = () => {
    let params = {};
    let search = location.search.substring(1);

    if (search) {
        const url = `{"${search.replace(/&/g, '","').replace(/=/g, '":"')}"}`;
        params = JSON.parse(url, (key, value) => {
            return key === "" ? value : decodeURIComponent(value)
        });
    }

    return params;
};

const isNumeric = (value) => {
    return !isNaN(parseFloat(value)) && isFinite(value);
};

/*******************************************************************************
 * @description Checks if value parameter is a function
 *
 * @param {*} value: Anything
 *
 * @return {boolean}: True if provided value is a function.
 */
const isFunction = (value) => {
    return typeof value === FUNCTION;
};

/*******************************************************************************
 * @description Checks to see if the passed parameter is of type 'Object' or
 * 'function'.
 *
 * @param {any} obj: Thing to check
 *
 * @return {boolean}: True if the provided obj is an object or a function.
 */
const isObject = (obj) => {
    return isFunction(obj) || typeof obj === OBJECT && !!obj;
};

/*******************************************************************************
 * @description Checks to see if the passed parameter is a primative.
 *
 * @param {any} value: Thing to check
 *
 * @return {boolean}: True if the provided obj is a primative.
 */
const isPrimative = (value) => {
    return (value !== Object(value));
}

/**
 * Check if a value is undefined.
 * @param value         Value to check
 * @returns {boolean}   TRUE when value is undefined.
 */
const isUndefined = (value) => {
    // void(0) allows us to safely obtain undefined to compare with the passed-in value
    return value === void (0);
};

/**
 * Check if a primitive is undefined, null or blank string.
 * @param value         Value to check.
 * @returns {boolean}   TRUE when the given value is undefined, null or blank string.
 */
const isEmpty = (value) => {
    return isUndefined(value) || value === null || value === '';
};

/**
 * Check if an object is empty
 * @param object         Object to check.
 * @returns {boolean}   TRUE when the given object is empty.
 */
const isEmptyObject = (object) => {
    for (let key in object) {
        if (object.hasOwnProperty(key)) return false;
    }
    return true;
}

/**
 * Inverse of isEmpty
 * @param value         Value to check.
 * @returns {boolean}   TRUE when the given value is not undefined, null or blank string.
 */
const isNotEmpty = (value) => {
    return !isEmpty(value);
};

const isNull = value => {
    return value === undefined || value === null;
};

/*******************************************************************************
 * @description Shallow clones the provided object.
 *
 * @param {object} obj: Object to clone
 *
 * @return {object}: Cloned object
 */
const mutable = (obj) => {
    return JSON.parse(JSON.stringify(obj));
};

/*******************************************************************************
 * @description Shifts an item in the array to a given index.
 *
 * @param {list} array: List of items.
 * @param {integer} oldIndex: Current index of the item to be moved.
 * @param {integer} newIndex: Index to move the item to.
 *
 * @return {list} array: Array with shifted items.
 */
const shiftToIndex = (array, oldIndex, newIndex) => {
    [array[oldIndex], array[newIndex]] = [array[newIndex], array[oldIndex]];
    return array;
};

/*******************************************************************************
 * @description Javascript method comparable to Apex's String.format(...).
 * Replaces placeholders in Custom Labels ({0}, {1}, etc) with provided values.
 *
 * @param {string} string: Custom Label to be formatted.
 * @param {array} replacements: List of string to use as replacements.
 * @return {string} formattedString: Formatted custom label
 */
const format = (string, replacements) => {
    let formattedString = isEmpty(string) ? '' : string;
    if (replacements) {
        let key;
        const type = typeof replacements;
        const args =
            'string' === type || 'number' === type
                ? Array.prototype.slice.call(replacements)
                : replacements;
        for (key in args) {
            if (args.hasOwnProperty(key)) {
                formattedString = formattedString.replace(
                    new RegExp('\\{' + key + '\\}', 'gi'),
                    args[key]
                );
            }
        }
    }

    return formattedString;
};

/*******************************************************************************
 * @description Removes an item in an array by a property.
 *
 * @param {list} array: List of items.
 * @param {string} property: Property to find by.
 * @param {string} value: Value of property to check against.
 */
const removeByProperty = (array, property, value) => {
    const index = array.findIndex(element => element[property] === value);
    if (index === -1) return;
    array.splice(index, 1);
};

/**
 * @description Removes an item from the given array based on a given value
 *
 * @param {array} array: List to remove an item from
 * @param {any} value: Value to match and remove from array
 */
const removeFromArray = (array, value) => {
    const index = array.findIndex(item => item === value);
    if (index === -1) return;
    array.splice(index, 1);
}

/*******************************************************************************
 * @description Loop through provided array or object properties. Recursively check
 * if the current value is an object or an array and copy accordingly.
 *
 * @param {any} src: Thing to clone
 *
 * @return {object} clone: Deep clone copy of src
 */
const deepClone = (src) => {
    let clone = null;

    if (isPrimative(src)) {
        return src;
    }

    if (isObject(src)) {
        clone = {};
        for (let property in src) {
            if (src.hasOwnProperty(property)) {
                // if the value is a nested object, recursively copy all it's properties
                clone[property] = isObject(src[property]) ? deepClone(src[property]) : src[property];
            }
        }
    }

    if (Array.isArray(src)) {
        clone = [];
        for (let item of src) {
            clone.push(deepClone(item));
        }
    }

    return clone;
}

/*******************************************************************************
 * @description Sorts the given list by field name and direction
 *
 * @param {array} list: List to be sorted
 * @param {string} property: Property to sort by
 * @param {string} sortDirection: Direction to sort by (i.e. 'asc' or 'desc')
 * @param {boolean} isNullsLast: If truthy, orders by NULLS LAST using isEmpty(value)
 *
 * @return {list} data: Sorted instance of list.
 */
const sort = (objects, attribute, direction = "desc", isNullsLast) => {
    if (objects && attribute) {
        objects = deepClone(objects);
        let aBeforeB, bBeforeA;
        {
            let sortDirectionMultiplier = direction.toLowerCase() === "desc" ? -1 : 1;

            aBeforeB = -1 * sortDirectionMultiplier;
            bBeforeA = 1 * sortDirectionMultiplier;
        }

        return objects.sort((a, b) => {
            if (isNull(a)) {
                if (isNull(b)) {
                    return 0;
                }
                return isNullsLast ? bBeforeA : aBeforeB;
            }
            if (isNull(b)) {
                return isNullsLast ? aBeforeB : bBeforeA;
            }
            if (isNull(a[attribute])) {
                if (isNull(b[attribute])) {
                    return 0;
                }
                return isNullsLast ? bBeforeA : aBeforeB;
            }
            if (isNull(b[attribute])) {
                return isNullsLast ? aBeforeB : bBeforeA;
            }
            if (a[attribute] < b[attribute]) {
                return aBeforeB;
            }
            if (b[attribute] < a[attribute]) {
                return bBeforeA;
            }
            return 0;
        });
    }
    return objects;
};

/*******************************************************************************
* @description Method checks to see if a property on the given object exists.
* Otherwise returns undefined.
*
* @param {object} object: Object with properties to check.
* @param {string} property: Name of the property to check.
* @return {list} remainingProperties: Destructure all other arguments so we can
* check N levels deep of the object.
* e.g. hasNestedProperty(someObject, 'firstLevel', 'secondLevel', 'thirdLevel')
*/
const hasNestedProperty = (object, property, ...remainingProperties) => {
    if (object === undefined || object === null) return false
    if (remainingProperties.length === 0 && object.hasOwnProperty(property)) return true
    return hasNestedProperty(object[property], ...remainingProperties)
}

/*******************************************************************************
* @description Method returns the value of a property on the given object.
* Otherwise returns undefined.
*
* @param {object} object: Object with properties to return.
* @return {list} args: Destructure all other arguments so we can
* check N levels deep of the object.
* e.g. getNestedProperty(someObject, 'firstLevel', 'secondLevel', 'thirdLevel')
*/
const getNestedProperty = (object, ...args) => {
    return args.reduce((obj, level) => obj && obj[level], object)
}

/*******************************************************************************
* @description Method attempts the key or value within an object by a key
* substring where the following happens.
*     objectToSearch = { "GAU_Allocation_1_asdfghj": value, "Account_1_asdfgh": value}
*     keyToFind = "GAU_Allocation_1_"
*     returnKey = true
* returns "GAU_Allocation_1_asdfghj".
*
* @param {object} objectToSearch: Object with properties to return.
* @param {string} keyToFind: Substring to check for.
* @param {boolean} returnKey: Determines whether we return the key or value of
* the object.
*/
const getLikeMatchByKey = (objectToSearch, keyToFind, returnKey = false) => {
    for (let key in objectToSearch) {
        if (key.toLowerCase().indexOf(keyToFind.toLowerCase()) !== -1)
            return returnKey ? key : objectToSearch[key];
    }
    return null;
}

/*******************************************************************************
* @description Methods checks if two arrays are strictly equal both in length
* and order of items.
*
* @param {list} arr1: An array.
* @param {list} arr2: An array.
*
* @return {boolean}: Returns true if the provided arrays are strictly equal.
*/
const arraysMatch = (arr1, arr2) => {
    if (arr1 && arr2) {
        if (arr1.length !== arr2.length) return false;

        for (var i = 0; i < arr1.length; i++) {
            if (arr1[i] !== arr2[i]) return false;
        }

        return true;
    }

    return false;
};

/*******************************************************************************
* @description Methods converts dot-notation strings provided by importing
* relationships like 'npe01__OppPayment__r.Name' from the schema into references.
*
* @param {object} obj: Object to pull a value from
* @param {string} dotNotationString: A string of references
*
* @return {boolean}: Returns true if the provided arrays are strictly equal.
*/
const getValueFromDotNotationString = (obj, dotNotationString) => {
    return dotNotationString.split('.').reduce((accumulator, currentValue) => accumulator[currentValue], obj);
}

/*******************************************************************************
 * @description Returns an object that contains a subset of the source object's
 *              properties.  Return includes related object data when present on the
 *              source object.
 */
const getSubsetObject = (sourceObj, propertyNames) => {
    const subsetObject = {};
    propertyNames.forEach(propertyName => {
        if (Object.keys(sourceObj).includes(propertyName)) {
            subsetObject[propertyName] = sourceObj[propertyName];

            if (Object.keys(sourceObj).includes(propertyName.replace('__c', '__r'))) {
                subsetObject[propertyName.replace('__c', '__r')] =
                    sourceObj[propertyName.replace('__c', '__r')];
            }
        }
    });
    return subsetObject;
}

/**
 * @description Parses the api name string of a custom
 *              object or field and returns its namespace.
 * @param apiName
 * @returns {String} The namespace of the passed-in object or field.
 *              Null if the object or field does not have a namespace.
 */
const getNamespace = (apiName) => {
    if (!apiName) return null;

    const apiNameParts = apiName.split('__');
    return apiNameParts.length === 3 ? apiNameParts[0] : null;
}

/*******************************************************************************
* @description Checks to see if provided string is parsable. If true, returns
* parsed string otherwise returns false.
*
* @param {string} str: String to parse
*/
const validateJSONString = (str) => {
    try {
        return JSON.parse(str);
    } catch (error) {
        return false;
    }
}

/***
 * @description Contruct error wrapper from the error event
 *   error.body is the error from apex calls
 *   error.body.output.errors is for AuraHandledException messages
 *   error.body.message errors is the error from wired service
 *   error.detail.output.errors is the error from record-edit-forms
 * @returns Object with header and detail to render in the UI
 */
const constructErrorMessage = (error) => {
    let header;
    let message;

    if (typeof error === 'string' || error instanceof String) {
        message = error;

    } else if (error.message) {
        message = error.message;

    } else if ((error.body && error.body.output)) {
        if (Array.isArray(error.body) &&
            !error.body.output.errors) {
            message = error.body.map(e => e.message).join(', ');

        } else if (typeof error.body.message === 'string' &&
            !error.body.output.errors) {
            message = error.body.message;

        } else if (error.body.output &&
            Array.isArray(error.body.output.errors)) {
            message = error.body.output.errors.map(e => e.message).join(', ');
        }

    } else if (error.detail && error.detail.output && Array.isArray(error.detail.output.errors)) {
        header = error.detail.message;
        message = error.detail.output.errors.map(e => e.message).join(', ');

    } else if (error.body && error.body.message) {
        message = error.body.message;
    }

    return {
        header: header || unknownErrorLabel,
        detail: message || unknownErrorLabel
    };
}

/*******************************************************************************
 * @description Creates and dispatches a ShowToastEvent
 *
 * @param {string} title: Title of the toast, displayed as a heading.
 * @param {string} message: Message of the toast. It can contain placeholders in
 * the form of {0} ... {N}. The placeholders are replaced with the links from
 * messageData param
 * @param {string} mode: Mode of the toast
 * @param {array} messageData: List of values that replace the {index} placeholders
 * in the message param
 */
const showToast = (title, message, variant, mode, messageData) => {
    const event = new ShowToastEvent({
        title: title,
        message: message,
        variant: variant,
        mode: mode,
        messageData: messageData
    });
    dispatchEvent(event);
}

/*******************************************************************************
 * @description Strips namespace prefix from object and field api names
 * @param apiName
 * @param namespacePrefix
 * @returns {*|string}
 */
const stripNamespace = (apiName, namespacePrefix) => {
    if (!apiName.startsWith(namespacePrefix)) {
        return apiName;
    }
    const apiNameParts = apiName.split(namespacePrefix);
    return apiNameParts[1];
}

/**
 * @description Replaces the last instance of "__c" with "__r".
 * Useful when referencing the related record field on objects
 * in the lightning/uiRecordApi Record format:
 * https://developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/ui_api_responses_record.htm
 * @param customFieldApiNameOrFieldReference
 * The ApiName of the relationship field for which the related record
 * field name is desired, or the field reference object.
 * https://developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/ui_api_responses_field_value.htm#ui_api_responses_field_value
 */
const relatedRecordFieldNameFor = (customFieldApiNameOrFieldReference) => {
    const fieldApiName =
        getFieldApiNameForFieldApiNameOrObjectReference(customFieldApiNameOrFieldReference);
    return fieldApiName &&
        replaceLastInstanceOfWith(fieldApiName, '__c', '__r');
}

/**
 * @description Replaces the last instance of a string pattern with another pattern.
 * @param subject The original string.
 * @param toRemove The pattern for which the last instance should be removed.
 * @param replacement The pattern used to replace the last instance of toRemove.
 * @returns {*|void|string} A new string with the last instance replaced.
 */
const replaceLastInstanceOfWith = (subject, toRemove, replacement) => {
    return subject && subject.replace(new RegExp(toRemove + '$'), replacement);
}

const apiNameFor = (objectOrFieldReference) => {
    if (objectOrFieldReference === null || objectOrFieldReference === undefined) {
        return objectOrFieldReference;
    }
    if (objectOrFieldReference.hasOwnProperty('fieldApiName')) {
        return objectOrFieldReference.fieldApiName;
    } else if (objectOrFieldReference.hasOwnProperty('objectApiName')) {
        return objectOrFieldReference.objectApiName;
    } else {
        return null;
    }
}

const isString = (val) => {
    return typeof val === 'string' || val instanceof String;
}

const getFieldApiNameForFieldApiNameOrObjectReference = (fieldApiNameOrFieldReference) => {
    return isString(fieldApiNameOrFieldReference) ?
        fieldApiNameOrFieldReference :
        apiNameFor(fieldApiNameOrFieldReference);
}

/**
 * @description Converts field describe info into a object that is easily accessible from the front end
 * Ignore errors to allow the UI to simply not render the layout-item if the field info doesn't exist
 * (i.e, the field isn't accessible).
 */
const extractFieldInfo = (fieldInfos, fldApiName) => {
    try {
        const field = fieldInfos[fldApiName];
        return {
            apiName: field.apiName,
            label: field.label,
            inlineHelpText: field.inlineHelpText,
            dataType: field.dataType
        };
    } catch (error) { }
}

/**
 * @description Method converts field describe info into objects that the
 * getRecord method can accept into its 'fields' parameter.
 */
const buildFieldDescribes = (fields, objectApiName) => {
    return Object.keys(fields).map((fieldApiName) => {
        return {
            fieldApiName: fieldApiName,
            objectApiName: objectApiName
        }
    });
}

const createPicklistOption = (label, value, attributes = null, validFor = []) => ({
    attributes: attributes,
    label: label,
    validFor: validFor,
    value: value
});

const nonePicklistOption = () => {
    return createPicklistOption(commonLabelNone, commonLabelNone);
}

export {
    apiNameFor,
    buildFieldDescribes,
    constructErrorMessage,
    debouncify,
    deepClone,
    extractFieldInfo,
    findIndexByProperty,
    getNamespace,
    getQueryParameters,
    getSubsetObject,
    isEmpty,
    isEmptyObject,
    isNotEmpty,
    isNumeric,
    isFunction,
    isObject,
    isUndefined,
    isPrimative,
    isNull,
    isString,
    mutable,
    sort,
    shiftToIndex,
    showToast,
    removeByProperty,
    removeFromArray,
    format,
    hasNestedProperty,
    getNestedProperty,
    getLikeMatchByKey,
    arraysMatch,
    getValueFromDotNotationString,
    validateJSONString,
    stripNamespace,
    relatedRecordFieldNameFor,
    nonePicklistOption,
    createPicklistOption,
    UtilDescribe
};


text:
/*************************************************************************
**                                                                      **
**  Description                                                         **
**                                                                      **
**  This GAMMA module provides functions for simulation of field        **
**  gradients in NMR spectroscopy. In particular, these functions       **
**  perform acquisitions of evenly spaced expectation values on a       **
**  a system in a field gradient.                                       **
**                                                                      **
*************************************************************************/

#ifndef   GrdAcq_cc_			// Is file already included?
#  define GrdAcq_cc_ 1			// If no, then remember it
#  if defined(GAMPRAGMA)		// Using the GNU compiler?
#    pragma implementation		// This is the implementation
#  endif

#include <Gradients/GrdAcquire.h>	// Include the interface
#include <HSLib/HSacquire.h>		// Include Hilbert space stuff
#include <Level2/acquire1D.h>		// Include class acquire1D
#include <vector>			// Include libstdc++ STL vectors

using std::vector;			// Using libstdc++ STL vectors

// ____________________________________________________________________________
// A                            FID Functions
// ____________________________________________________________________________

/* These functions generate time domain acquisitions based on the GAMMA FID
   functions. That is, they require user specification of the Hamiltonians
   that evolve the system (all subsystems), the initial state of the system
   (all subsystems), the detection operator, and the (dwell) time between
   points in the acquisition.  The functions will automatically sum over all
   sub-systems in the field gradient. Note that the format and names of these
   functions mirror those found in the GAMMA Hilbert Space Library Module
   (src/HSLib/HSacquire.*)  Note thate here each subsystem is assumed ot have
   its own Hamiltonian which may alter the system transitions by more than
   simply off-setting their frequencies.                                     */

// ----------------------------------------------------------------------------
//              Functions Which Take A row_vector As An Argument
//                               (acquire == FID)
// ----------------------------------------------------------------------------

void acquire(vector<gen_op>& sigmas, gen_op& D, vector<gen_op>& Hs,
                                         double td, int t2pts, row_vector& fid)
  { FID(sigmas, D, Hs, td, t2pts, fid); }

void acquire(vector<gen_op>& sigmas, gen_op& D, vector<gen_op>& Us,
                                                    int t2pts, row_vector& fid)
  { FID(sigmas, D, Us, t2pts, fid); }

void FID(vector<gen_op>& sigmas, gen_op& D, vector<gen_op>& Hs,
                                         double td, int t2pts, row_vector& fid)
  {
  unsigned nss = sigmas.size();			// # of sub-systems
  row_vector data0(fid.size(),complex0);	// Empty data block
  fid = data0;					// Zero input data block
  row_vector data, datasum = data0; 		// Working data vectors
  for(unsigned i=0; i<nss; i++)			// Loop over spin systems
    {
    data = data0;				//   Zero working block
    FID(sigmas[i],D,Hs[i],td,t2pts,data);	//   Perform acquisition
    datasum += data;				//   Sum with previous
    }
  if(data.size() >= fid.size()) fid = data;	// Copy to fid if block bigger
  else						// Else copy only generated
    {						// acquisition points
    for(int j=0; j<t2pts; j++)
      fid.put(data.get(j), j);
    }
  }

void FID(vector<gen_op>& sigmas, gen_op& D, vector<gen_op>& Us,
                                                    int t2pts, row_vector& fid)
  {
  unsigned nss = sigmas.size();			// # of sub-systems
  row_vector data0(fid.size(),complex0);	// Empty data block
  fid = data0;					// Zero input data block
  row_vector data, datasum = data0; 		// Working data vectors
  for(unsigned i=0; i<nss; i++)			// Loop over spin systems
    {
    data = data0;				//   Zero working block
    FID(sigmas[i],D,Us[i],t2pts,data);		//   Perform acquisition
    datasum += data;				//   Sum with previous
    }
  if(data.size() >= fid.size()) fid = data;	// Copy to fid if block bigger
  else						// Else copy only generated
    {						// acquisition points
    for(int j=0; j<t2pts; j++)
      fid.put(data.get(j), j);
    }
  }

// ----------------------------------------------------------------------------
//                      Functions Which Return A row_vector
//                                (acquire == FID)
// ----------------------------------------------------------------------------

row_vector acquire(vector<gen_op>& sigmas, gen_op& D, vector<gen_op>& Hs,
                                                         double td, int t2pts)
  { return FID(sigmas, D, Hs, td, t2pts); }

row_vector acquire(vector<gen_op>& sigmas, gen_op& D, vector<gen_op>& Us,
                                                                    int t2pts)
  { return FID(sigmas, D, Us, t2pts); }

row_vector FID(vector<gen_op>& sigmas, gen_op& D, vector<gen_op>& Hs,
                                                         double td, int t2pts)
  {
  unsigned nss = sigmas.size();			// # of sub-systems
  row_vector data(t2pts,complex0);		// Data block for acquire
  for(unsigned i=0; i<nss; i++)			// Loop over spin systems
    data += FID(sigmas[i],D,Hs[i],td,t2pts);	// and sum each acquisiiton
  return data;					// Return the propagators
  }

row_vector FID(vector<gen_op>& sigmas, gen_op& D, vector<gen_op>& Us,
                                                                    int t2pts)
  {
  unsigned nss = sigmas.size();			// # of sub-systems
  row_vector data(t2pts,complex0);		// Data block for acquire
  for(unsigned i=0; i<nss; i++)			// Loop over spin systems
    data += FID(sigmas[i],D,Us[i],t2pts);	// and sum each acquisiiton
  return data;					// Return the propagators
  }

// ----------------------------------------------------------------------------
//               Functions Which Include Phenomenological Relaxation
//                                (acquire == FID)
// ----------------------------------------------------------------------------

row_vector acquire(RBasic& RB, vector<gen_op>& sigmas,
                           gen_op& D, vector<gen_op>& Hs, double td, int t2pts)
  { return FID(RB,sigmas,D,Hs,td,t2pts); }

row_vector FID(RBasic& RB, vector<gen_op>& sigmas,
                           gen_op& D, vector<gen_op>& Hs, double td, int t2pts)
  {
  RB.SetDet(D);					// Set detection operator
  int nss = sigmas.size();			// Number of subsystems
  row_vector data(t2pts, complex0);		// Data block for FID
  for(int i=0; i<nss; i++)			// Loop over all subsystems
    {
    RB.SetH0(Hs[i]);                            //   Set Hamiltonian in FID
    data += RB.FID(sigmas[i],td,t2pts); 	//   Acquisition
    }
  return data;
  }

// ____________________________________________________________________________
// B                       Class Acquire1D Functions
// ____________________________________________________________________________

/* The funcitons in the previous section essentially duplicated the GAMMA FID
   functionality when there is no gradient. The functions in this section
   cannot duplicate those provided by class acquire1D because we cannot be
   member functions of that class. Rather we just make use of the class as
   best we can to provide users with the main abilities if acquire1D.        */

row_vector acquire1DT(gen_op& D, vector<gen_op>& Hs,
                      vector<gen_op>& sigmas, int t2pts, double td, bool norm)
  {
  unsigned nss = sigmas.size();			// # of sub-systems
  row_vector data;				// Data block for acquire
  for(unsigned i=0; i<nss; i++)			// Loop over spin systems
    {
    acquire1D ACQ(D, Hs[i]);			//   Prepare for acquisition
    data += ACQ.T(sigmas[i],t2pts,-td);		//   Sum up sub-system FID's
    }
  if(norm) data /= nss;				// Normalized if desired
  return data;					// Return the propagators
  }

row_vector acquire1DT(gen_op& D, vector<gen_op>& Hs,
                               gen_op& sigmas, int t2pts, double td, bool norm)
  {
  unsigned nss = Hs.size();			// # of sub-systems
  row_vector data;				// Data block for acquire
  for(unsigned i=0; i<nss; i++)			// Loop over spin systems
    {
    acquire1D ACQ(D, Hs[i]);			//   Prepare for acquisition
    data += ACQ.T(sigmas,t2pts,-td);		//   Sum up sub-system FID's
    }
  if(norm) data /= nss;				// Normalized if desired
  return data;					// Return the propagators
  }

// ____________________________________________________________________________
// X                    Single Point Detection Functions
// ____________________________________________________________________________

complex detect(gen_op& D, vector<gen_op>& sigmas)
  {
  unsigned nss = sigmas.size();			// # of sub-systems
  complex z(0);					// Point that is detected
  for(unsigned i=0; i<nss; i++)			// Loop over spin systems
    z += trace(D, sigmas[i]);
  return z;
  }

#endif 								// GrdAcquire.cc


text:
<!DOCTYPE HTML>

    <title>Dragon Age GM</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <link type="text/css" rel="stylesheet" href="./css/bootstrap-select.min.css">
    <link type="text/css" rel="stylesheet" href="./css/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="./css/bootstrap-switch.min.css">
    <link type="text/css" rel="stylesheet" href="./css/jquery.treegrid.css">
    <link type="text/css" rel="stylesheet" href="./css/style.css">

                Initiative Tracker

                <button class="btn btn-default btn-xs" type="button" id="add_all" style="width:100%;">Add all</button>

                <button class="btn btn-default btn-xs" type="button" id="advance" style="width:100%;">Advance</button>

                Round #: 0

                      Name

                Players

                      Name
                      Def.
                      Arm.
                      Sp.
                      Init.

                        <input type="file" multiple id="player_upload" style="display:none;">
                        <button class="btn btn-default btn-xs" type="button" id="add_player" style="width:100%">+</button>

                Foes

                      Name
                      Def.
                      Arm.
                      Sp.
                      Init.

                        <input type="file" multiple id="foe_upload" style="display:none;">

                            Multi. <input type="checkbox" id="foe_multi">

                          <button class="btn btn-default btn-xs" type="button" id="add_foe" style="width:100%">+</button>

          <input type="text" class="form-control is-int" id="add_remove_value" style="width:100%">

              <button class="btn btn-default" type="button" id="add">+</button>

              <button class="btn btn-default" type="button" id="remove">-</button>

How many would you like to add?

                <input type="text" class="form-control is-int" id="add_foe_value" style="width:100%" value="1">

            <button type="button" class="btn btn-default" data-dismiss="modal" id="upload_foe">Upload</button>


text:
package org.dylanfoundry.deft.library;

import com.intellij.CommonBundle;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.libraries.NewLibraryConfiguration;
import com.intellij.openapi.roots.libraries.ui.OrderRoot;
import com.intellij.openapi.roots.ui.configuration.libraryEditor.LibraryEditor;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import org.dylanfoundry.deft.registry.DeftRegistryEntryInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class LibraryAttachHandler {
  @Nullable
  public static NewLibraryConfiguration chooseLibrary(final @NotNull Project project,
                                                      JComponent parentComponent) {
    LibraryAttachDialog dialog = new LibraryAttachDialog(project);
    dialog.setTitle("Attach Library");
    dialog.show();
    if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) {
      return null;
    }

    NewLibraryConfiguration configuration = attachLibrary(project, dialog.getRegistryEntries());
    if (configuration == null) {
      Messages.showErrorDialog(parentComponent, "No libraries attached", CommonBundle.getErrorTitle());
    }
    return configuration;
  }

  @Nullable
  public static NewLibraryConfiguration attachLibrary(final @NotNull Project project,
                                                      List<DeftRegistryEntryInfo> registryEntries) {
    final Ref<NewLibraryConfiguration> result = Ref.create(null);

    for (DeftRegistryEntryInfo registryEntry : registryEntries) {
      AccessToken accessToken = WriteAction.start();
      try {
        final List<OrderRoot> roots = createRoots(registryEntry);

        result.set(new NewLibraryConfiguration(registryEntry.getLibraryName(),
                       DeftLibraryType.getInstance(),
                       new DeftLibraryProperties(registryEntry.getLibraryName())) {
                           @Override
                           public void addRoots(@NotNull LibraryEditor editor) {
                             editor.addRoots(roots);
                           }
                         });
      } finally {
        accessToken.finish();
      }
    }

    return result.get();
  }

  public static List<OrderRoot> createRoots(@NotNull DeftRegistryEntryInfo registryInfo) {
    final List<OrderRoot> result = new ArrayList<OrderRoot>();
    final VirtualFileManager manager = VirtualFileManager.getInstance();

    File repoFolder = new File(registryInfo.getLocation());
    final String url = VfsUtil.getUrlForLibraryRoot(repoFolder);
    final VirtualFile file = manager.refreshAndFindFileByUrl(url);
    if (file != null) {
      OrderRootType rootType = OrderRootType.SOURCES;
      result.add(new OrderRoot(file, rootType));
    }

    return result;
  }

}


text:
Basic CPU implementation of an LSTM Sparse forward pass.
Prerequisites :
    You need to turn on MKL wrappers and give the path to MKL by setting MKL_PREFIX, these can be done in the tiramisu/configure.cmake file.

Run the benchmark :

  From the build directory tiramisu/build/benchmarks/DNN/blocks/LSTM/cpu_lib_sparse/ execute:
    make

  - wrapper_lstm_sparse file is generated in tiramisu/benchmarks/DNN/blocks/LSTM/cpu_lib_sparse/

  To compare to MKLDNN, run ./compile_and_run_mkldnn.sh, then run ./wrapper_lstm_sparse
  To compare to MKL Sparse, run ./compile_and_run_mkl_sparse.sh intel64 then run ./wrapper_lstm_sparse (here intel64 can be something else depending on the architecture)


text:
title: "Inspiring Faces Want to Know"
excerpt: "Finding inspiration from the faces of strangers on Sktchy for iOS."
image:
  path: &image /assets/images/sktchys-of-me-feature.jpg
  feature: *image
  teaser: /assets/images/sktchys-of-me-teaser.jpg
  thumb: /assets/images/sktchy-app-thumb.png
tags: [Sktchy, drawing, technology]
comments: false
---

It's been a lot of fun drawing the faces of strangers. But you know what's even better'? Having strangers draw you in return.

If you have an iOS device I encourage you to download the free [**Sktchy** app](http://www.sktchy.com/). You don't have to be an artist to use it --- in fact most using the app aren't. You just need to upload a selfie or two and hopefully inspire someone to create a work of art based on it.

I've been known to peruse the *Inspiration* tab in look of faces to draw. So if you've been patiently waiting for me to draw you as part of my [PaperFaces Project]({{ site.url }}{% post_url /articles/2012-08-31-paperfaces-ipad-portrait-project %}), Sktchy might be a nice alternative.

#### Beard Selfies are a Must
Goofy homeless looking beards help get you noticed. Apparently Sktchy artists enjoy them because mine has managed to inspire a handful of drawings and sketches. Who knew?


text:
echo "Starting Auditd"

exec /sbin/auditd -n

echo "Adding custom rules"

exec /sbin/auditctl -R /etc/audit/rules.d/custom.rules
#exec /sbin/auditctl -R /data/audit/custom.rules
exec /sbin/auditctl -l


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.google.android.gms.example.bannerexample.AdFreeActivity">
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:orderInCategory="100"
          app:showAsAction="never"/>
</menu>


text:
cask v1: 'on-the-job' do
  version :latest
  sha256 :no_check

  url 'http://stuntsoftware.com/downloads/OnTheJob.zip'
  name 'On The Job'
  appcast 'http://stuntsoftware.com/PHP/sparkle/onthejob.php',
          sha256: 'dc68765c1d326ba50aeda9af4ed46c208c6c0b9a85379eb71be0ba3a92887bd0'
  homepage 'http://stuntsoftware.com/onthejob/'
  license :commercial

  app 'On The Job.app'
end


text:
ghc --make Setup
./Setup configure --prefix=`pwd`/install --bindir='$prefix' --libdir='$prefix' --datadir='$prefix'
./Setup build
./Setup install
echo Now zip up `pwd`/install as "haddock-<version>-Win32.zip"


text:
module Azure::ApiManagement::Mgmt::V2019_01_01
  module Models
    #
    # Defines values for UserState
    #
    module UserState
      Active = "active"
      Blocked = "blocked"
      Pending = "pending"
      Deleted = "deleted"
    end
  end
end


text:
require 'test/unit'
require 'flexmock'
require 'test/redirect_error'

class TestNewInstances < Test::Unit::TestCase
  include FlexMock::TestCase
  include FlexMock::RedirectError

  class Dog
    def bark
      :woof
    end
    def wag
      :tail
    end
    def self.make
      new
    end
  end

  class Cat
    attr_reader :name
    def initialize(name, &block)
      @name = name
      block.call(self) if block_given?
    end
  end

  class Connection
    def initialize(*args)
      yield(self) if block_given?
    end
    def send(args)
      post(args)
    end
    def post(args)
      :unstubbed
    end
  end

  def test_new_instances_allows_stubbing_of_existing_methods
    flexstub(Dog).new_instances do |obj|
      obj.should_receive(:bark).and_return(:whimper)
    end
    m = Dog.new
    assert_equal :whimper,  m.bark
  end

  def test_new_instances_stubs_still_have_existing_methods
    flexstub(Dog).new_instances do |obj|
      obj.should_receive(:bark).and_return(:whimper)
    end
    m = Dog.new
    assert_equal :tail,  m.wag
  end

  def test_new_instances_will_pass_args_to_new
    flexstub(Cat).new_instances do |obj|
      obj.should_receive(:meow).and_return(:scratch)
    end
    x = :not_called
    m = Cat.new("Fido") { x = :called }
    assert_equal :scratch,  m.meow
    assert_equal "Fido", m.name
    assert_equal :called, x
  end

  # Some versions of the software had problems invoking the block after a
  # second stubbing.
  def test_new_gets_block_after_restubbing
    flexstub(Cat).new_instances { }
    x = :not_called
    m = Cat.new("Fido") { x = :called }
    assert_equal :called, x
    flexmock_teardown

    flexstub(Cat).new_instances { }
    x = :not_called
    m = Cat.new("Fido") { x = :called }
    assert_equal :called, x
  end

  def test_new_instances_stub_verification_happens_on_teardown
    flexstub(Dog).new_instances do |obj|
      obj.should_receive(:bark).once.and_return(nil)
    end

    fido = Dog.new
    ex = assert_raise(Test::Unit::AssertionFailedError) { flexmock_teardown }
    assert_match(/method 'bark\(.*\)' called incorrect number of times/, ex.message)
  end

  def test_new_instances_reports_error_on_non_classes
    ex = assert_raise(ArgumentError) {
      flexstub(Dog.new).new_instances do |obj|
        obj.should_receive(:hi)
      end
    }
    assert_match(/Class/, ex.message)
    assert_match(/new_instances/, ex.message)
  end

  def test_does_not_by_default_stub_objects_created_with_allocate
    flexstub(Dog).new_instances do |obj|
      obj.should_receive(:bark).and_return(:whimper)
    end
    m = Dog.allocate
    assert_equal :woof,  m.bark
  end

  def test_can_explicitly_stub_objects_created_with_allocate
    flexstub(Dog).new_instances(:allocate) do |obj|
      obj.should_receive(:bark).and_return(:whimper)
    end
    m = Dog.allocate
    assert_equal :whimper,  m.bark
  end

  def test_can_stub_objects_created_with_arbitrary_class_methods
    flexstub(Dog).new_instances(:make) do |obj|
      obj.should_receive(:bark).and_return(:whimper)
    end
    assert_equal :whimper,  Dog.make.bark
  end

  def test_stubbing_arbitrary_class_methods_leaves_new_alone
    flexstub(Dog).new_instances(:make) do |obj|
      obj.should_receive(:bark).and_return(:whimper)
    end
    assert_equal :woof,  Dog.new.bark
  end

  def test_stubbing_new_and_allocate_doesnt_double_stub_objects_on_new
    counter = 0
    flexstub(Dog).new_instances do |obj|
      counter += 1
    end
    Dog.new
    assert_equal 1, counter
  end

  # Current behavior does not install stubs into the block passed to new.
  # This is rather difficult to achieve, although it would be nice.  For the
  # moment, we assure that they are not stubbed, but I am willing to change
  # this in the future.
  def test_blocks_on_new_do_not_have_stubs_installed
    flexstub(Connection).new_instances do |new_con|
      new_con.should_receive(:post).and_return {
        :stubbed
      }
    end
    block_run = false
    Connection.new do |c|
      assert_equal :unstubbed, c.send("hi")
      block_run = true
    end
    assert block_run
  end

  def test_new_instances_accept_chained_expectations
    flexmock(Dog).new_instances.
      should_receive(:growl).and_return(:grr).
      should_receive(:roll_over).and_return(:flip)
    assert_equal :grr, Dog.new.growl
    assert_equal :flip, Dog.new.roll_over
  end

  def test_fancy_use_of_chained_should_received
    flexmock(Dog).new_instances.should_receive(:woof => :grrr)
    assert_equal :grrr, Dog.new.woof
  end

  def test_writable_accessors
    flexmock(Dog).new_instances.should_receive(:name=).with("fido")
    dog = Dog.new
    dog.name = 'fido'
  end

  def test_ordering_can_be_specified
    dog = Dog.new
    flexmock(dog).should_receive(:bark).once.ordered
    flexmock(dog).should_receive(:bite).once.ordered
    dog.bark
    dog.bite
  end

  def test_ordering_can_be_specified_in_groups
    dog = Dog.new
    flexmock(dog).should_receive(:wag).once.ordered(:safe)
    flexmock(dog).should_receive(:bark).once.ordered(:danger)
    flexmock(dog).should_receive(:bite).once.ordered(:danger)
    dog.wag
    dog.bite
    dog.bark
  end
end