text:
import runloop from 'global/runloop';
import log from 'utils/log/log';
import isEqual from 'utils/isEqual';
import UnresolvedDependency from 'viewmodel/Computation/UnresolvedDependency';

var Computation = function ( ractive, key, signature ) {
	this.ractive = ractive;
	this.viewmodel = ractive.viewmodel;
	this.key = key;

	this.getter = signature.get;
	this.setter = signature.set;

	this.hardDeps = signature.deps || [];
	this.softDeps = [];
	this.unresolvedDeps = {};

	this.depValues = {};

	if ( this.hardDeps ) {
		this.hardDeps.forEach( d => ractive.viewmodel.register( d, this, 'computed' ) );
	}

	this._dirty = this._firstRun = true;
};

Computation.prototype = {
	constructor: Computation,

	init: function () {
		var initial;

		this.bypass = true;

		initial = this.ractive.viewmodel.get( this.key );
		this.ractive.viewmodel.clearCache( this.key );

		this.bypass = false;

		if ( this.setter && initial !== undefined ) {
			this.set( initial );
		}
	},

	invalidate: function () {
		this._dirty = true;
	},

	get: function () {
		var ractive, newDeps, dependenciesChanged, dependencyValuesChanged = false;

		if ( this.getting ) {
			// prevent double-computation (e.g. caused by array mutation inside computation)
			return;
		}

		this.getting = true;

		if ( this._dirty ) {
			ractive = this.ractive;

			// determine whether the inputs have changed, in case this depends on
			// other computed values
			if ( this._firstRun || ( !this.hardDeps.length && !this.softDeps.length ) ) {
				dependencyValuesChanged = true;
			} else {
				[ this.hardDeps, this.softDeps ].forEach( deps => {
					var keypath, value, i;

					if ( dependencyValuesChanged ) {
						return;
					}

					i = deps.length;
					while ( i-- ) {
						keypath = deps[i];
						value = ractive.viewmodel.get( keypath );

						if ( !isEqual( value, this.depValues[ keypath ] ) ) {
							this.depValues[ keypath ] = value;
							dependencyValuesChanged = true;

							return;
						}
					}
				});
			}

			if ( dependencyValuesChanged ) {
				ractive.viewmodel.capture();

				try {
					this.value = this.getter.call( ractive );
				} catch ( err ) {
					log.warn({
						debug: ractive.debug,
						message: 'failedComputation',
						args: {
							key: this.key,
							err: err.message || err
						}
					});

					this.value = void 0;
				}

				newDeps = ractive.viewmodel.release();
				dependenciesChanged = this.updateDependencies( newDeps );

				if ( dependenciesChanged ) {
					[ this.hardDeps, this.softDeps ].forEach( deps => {
						deps.forEach( keypath => {
							this.depValues[ keypath ] = ractive.viewmodel.get( keypath );
						});
					});
				}
			}

			this._dirty = false;
		}

		this.getting = this._firstRun = false;
		return this.value;
	},

	set: function ( value ) {
		if ( this.setting ) {
			this.value = value;
			return;
		}

		if ( !this.setter ) {
			throw new Error( 'Computed properties without setters are read-only. (This may change in a future version of Ractive!)' );
		}

		this.setter.call( this.ractive, value );
	},

	updateDependencies: function ( newDeps ) {
		var i, oldDeps, keypath, dependenciesChanged, unresolved;

		oldDeps = this.softDeps;

		// remove dependencies that are no longer used
		i = oldDeps.length;
		while ( i-- ) {
			keypath = oldDeps[i];

			if ( newDeps.indexOf( keypath ) === -1 ) {
				dependenciesChanged = true;
				this.viewmodel.unregister( keypath, this, 'computed' );
			}
		}

		// create references for any new dependencies
		i = newDeps.length;
		while ( i-- ) {
			keypath = newDeps[i];

			if ( oldDeps.indexOf( keypath ) === -1 && ( !this.hardDeps || this.hardDeps.indexOf( keypath ) === -1 ) ) {
				dependenciesChanged = true;

				// if this keypath is currently unresolved, we need to mark
				// it as such. TODO this is a bit muddy...
				if ( isUnresolved( this.viewmodel, keypath ) && ( !this.unresolvedDeps[ keypath ] ) ) {
					unresolved = new UnresolvedDependency( this, keypath );
					newDeps.splice( i, 1 );

					this.unresolvedDeps[ keypath ] = unresolved;
					runloop.addUnresolved( unresolved );
				} else {
					this.viewmodel.register( keypath, this, 'computed' );
				}
			}
		}

		if ( dependenciesChanged ) {
			this.softDeps = newDeps.slice();
		}

		return dependenciesChanged;
	}
};

function isUnresolved( viewmodel, keypath ) {
	var key = keypath.split( '.' )[0];

	return !( key in viewmodel.ractive.data ) &&
	       !( key in viewmodel.computations ) &&
	       !( key in viewmodel.mappings );
}

export default Computation;


text:
package client

import (
	"testing"

	"github.com/Shopify/sarama"
	"github.com/onsi/gomega"

	"go.ligato.io/cn-infra/v2/logging/logrus"
)

func ExampleSyncProducer() {
	// init config
	config := NewConfig(logrus.DefaultLogger())
	config.ProducerConfig().Producer.RequiredAcks = sarama.WaitForAll
	config.SetBrokers("localhost:9091", "localhost:9092")

	// init client
	sClient, err := NewClient(config, Hash)
	if err != nil {
		return
	}

	// init producer
	producer, err := NewSyncProducer(config, sClient, Hash, nil)
	if err != nil {
		log.Errorf("NewSyncProducer errored: %v\n", err)
		return
	}

	// send message
	_, err = producer.SendMsgByte("test-topic", nil, []byte("test message"))
	if err != nil {
		log.Errorf("SendMsg errored: %v", err)
	}

	// close producer and release resources
	err = producer.Close()
	if err != nil {
		log.Errorf("SyncProducer close errored: %v", err)
		return
	}
	log.Info("SyncProducer closed")
}

func TestSyncProducer(t *testing.T) {
	gomega.RegisterTestingT(t)

	const topic string = "test"
	sp, mock := GetSyncProducerMock(t)

	mock.ExpectSendMessageAndSucceed()

	msg, err := sp.SendMsgByte(topic, []byte("key"), []byte("value"))
	gomega.Expect(msg).NotTo(gomega.BeNil())
	gomega.Expect(err).To(gomega.BeNil())
}

redpajama_set_name: RedPajamaGithub


text:
package io.kubernetes.client.util.generic;

import io.kubernetes.client.common.KubernetesType;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.models.V1Status;
import java.net.HttpURLConnection;

public class KubernetesApiResponse<DataType extends KubernetesType> {

  private final DataType object;
  private final V1Status status;
  private final int httpStatusCode;

  public KubernetesApiResponse(DataType object) {
    this.object = object;
    this.status = null;
    this.httpStatusCode = HttpURLConnection.HTTP_OK; // 200
  }

  public KubernetesApiResponse(V1Status status, int httpStatusCode) {
    this.object = null;
    this.status = status;
    this.httpStatusCode = httpStatusCode;
  }

  public DataType getObject() {
    return object;
  }

  public V1Status getStatus() {
    return status;
  }

  public int getHttpStatusCode() {
    return httpStatusCode;
  }

  public boolean isSuccess() {
    return this.httpStatusCode < HttpURLConnection.HTTP_BAD_REQUEST; // 400
  }

  /**
   * Throws api exception kubernetes api response on failure. This is the recommended approach to
   * deal with errors returned from server.
   *
   * @return the kubernetes api response
   * @throws ApiException the api exception
   */
  public KubernetesApiResponse<DataType> throwsApiException() throws ApiException {
    return onFailure(
        (code, errorStatus) -> {
          throw new ApiException(code, errorStatus.toString());
        });
  }

  /**
   * Calling errorStatusHandler upon errors from server..
   *
   * @param errorStatusHandler the error status handler
   * @return the kubernetes api response
   * @throws ApiException the api exception
   */
  public KubernetesApiResponse<DataType> onFailure(ErrorStatusHandler errorStatusHandler)
      throws ApiException {
    if (!isSuccess()) {
      errorStatusHandler.handle(this.getHttpStatusCode(), this.status);
    }
    return this;
  }

  public interface ErrorStatusHandler {
    void handle(int code, V1Status errorStatus) throws ApiException;
  }
}


text:
package org.apache.derbyTesting.functionTests.tests.compatibility;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import junit.framework.Test;

import org.apache.derby.drda.NetworkServerControl;

import org.apache.derbyTesting.junit.BaseTestCase;
import org.apache.derbyTesting.junit.BaseTestSetup;
import org.apache.derbyTesting.junit.DerbyDistribution;
import org.apache.derbyTesting.junit.DerbyVersion;
import org.apache.derbyTesting.junit.NetworkServerTestSetup;
import org.apache.derbyTesting.junit.SpawnedProcess;
import org.apache.derbyTesting.junit.TestConfiguration;

/**
 * Starts a network server of the specified Derby version.
 */
public class VersionedNetworkServerTestSetup
        extends BaseTestSetup {

    /** The first version to support '-noSecurityManager'. */
    private static final DerbyVersion SUPPORTS_NO_SECMAN_ARG =
            new DerbyVersion(10, 3, 1, 4);
    /**
     * The first version that supports the optional arguments on shutdown.
     *

     * See DERBY-4786 and related issues.
     */
    private static final DerbyVersion NO_BROKEN_SHUTDOWN =
            new DerbyVersion(10, 4, 0, 0);
    /** The Derby distribution to use. */
    private final DerbyDistribution dist;
    /** Paths for code to append to the server classpath. */
    private final String appendToClasspath;
    private SpawnedProcess spawned;
    private NetworkServerControl networkServerControl;

    public VersionedNetworkServerTestSetup(Test test, DerbyDistribution dist,
            String appendToClasspath) {
        super(test);
        this.dist = dist;
        this.appendToClasspath = appendToClasspath;
    }

    @Override
    public void setUp() {
        int port = TestConfiguration.getCurrent().getPort();
        try {
            networkServerControl =
                    NetworkServerTestSetup.getNetworkServerControl(port);
        } catch (Exception e) {
            fail(e.getMessage());
        }
        // Make sure there is no server up already (on our port).
        println("checking for running server on port " + port);
        if (ping(false, null)) {
            fail("a server is already running at port " + port);
        }

        // java -classpath ... org.apache.derby.drda...
        // Don't use -jar derbyrun.jar because we may need additional classes
        // to be on the classpath.
        String classpath = dist.getProductionClasspath() +
                (appendToClasspath == null
                            ? ""
                            : File.pathSeparator + appendToClasspath);
        ArrayList<String> cmd = new ArrayList<String>();
        cmd.add("org.apache.derby.drda.NetworkServerControl");
        cmd.add("start");
        cmd.add("-p");
        cmd.add(Integer.toString(port));
        if (dist.getVersion().compareTo(SUPPORTS_NO_SECMAN_ARG) >= 0) {
            cmd.add("-noSecurityManager");
        }

        Process proc = null;
        try {
            proc = BaseTestCase.execJavaCmd(null, classpath,
                cmd.toArray(new String[cmd.size()]), null);
        } catch (IOException ioe) {
            fail("failed to start server: " + ioe.getMessage());
        }
        spawned = new SpawnedProcess(proc, "NetworkServerControl");
        boolean pingOk = ping(true, proc);
        assertTrue(spawned.getFailMessage("server failed to come up"), pingOk);
        println("--- Server " + dist.getVersion() + " up");
    }

    @Override
    public void tearDown() {
        String errorMsg = null;
        boolean sawError = false;
        if (dist.getVersion().compareTo(NO_BROKEN_SHUTDOWN) < 0) {
            // We have to fork off a process to shut down the server.
            errorMsg = shutDownInSeparateProcess();
            sawError = errorMsg != null;
        } else {
            boolean pingOk = ping(true, spawned.getProcess());
            if (pingOk) {
                try {
                    networkServerControl.shutdown();
                } catch (Exception e) {
                    String msg = spawned.getFailMessage("shutdown failed");
                    errorMsg = " (failed to shut down server (" +
                            dist.getVersion().toString() + "): " +
                            e.getMessage() + " :: " + msg + ")";
                    sawError = true;
                }
            }
        }

        try {
            spawned.complete(5*1000);
        } catch (Exception e) {
            errorMsg = "process didn't die: " + e.getMessage() + (sawError ?
                    errorMsg : "");
            sawError = true;
        }
        networkServerControl = null;
        spawned = null;

        try {
            BaseTestCase.assertDirectoryDeleted(new File("wombat"));
        } catch (AssertionError ae) {
            // Catch this to generate a more complete error message.
            if (sawError) {
                errorMsg += " :: " + ae.getMessage();
            } else {
                throw ae;
            }
        }
        if (sawError) {
            fail(errorMsg);
        }
    }

    /**
     * Spawns a separate JVM process to shut down the running server using the
     * code distributed with the release.
     *

     * This method was added because some versions of Derby cannot be shut down
     * using code from a newer release.
     *
     * @return An error message, or {@code null} if no errors.
     */
    private String shutDownInSeparateProcess() {
        int port = TestConfiguration.getCurrent().getPort();
        // java -classpath ... org.apache.derby.drda...
        ArrayList<String> cmd = new ArrayList<String>();
        cmd.add("org.apache.derby.drda.NetworkServerControl");
        cmd.add("shutdown");
        cmd.add("-p");
        cmd.add(Integer.toString(port));
        if (dist.getVersion().compareTo(SUPPORTS_NO_SECMAN_ARG) >= 0) {
            cmd.add("-noSecurityManager");
        }
        Process proc;
        try {
            proc = BaseTestCase.execJavaCmd(null, dist.getProductionClasspath(),
                    cmd.toArray(new String[cmd.size()]), null);
        } catch (IOException ioe) {
            return "shutdown process failed to start: " + ioe.getMessage();
        }

        SpawnedProcess spawnedShutdown =
                new SpawnedProcess(proc, "shutdown process");
        int exitCode = -1;
        try {
            exitCode = spawnedShutdown.complete(10*1000L);
        }  catch (IOException ioe) {
            fail(spawnedShutdown.getFailMessage("shutdown process failed"));
        }
        if (exitCode == 0) {
            return null;
        } else {
            return spawnedShutdown.getFailMessage("abnormal process exit");
        }
    }

    /**
     * Pings the server.
     *
     * @param exepectServerUp whether the server is expected to be up or down
     * @param proc the process in which the server runs (may be {@code null})
     * @return Whether the ping is considered ok, which is determined by the
     *      response or lack of response from the server and the value of
     *      {@code expectedServerUp}.
     */
    private boolean ping(boolean exepectServerUp, Process proc) {
        boolean pingOk = false;
        try {
            pingOk = NetworkServerTestSetup.pingForServerUp(
                networkServerControl, proc, exepectServerUp);
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
        return pingOk;
    }

    private static void println(String msg) {
        BaseTestCase.println(msg);
    }
}


text:
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.outlook;
import com.wilutions.com.*;

/**
 * OlTaskRecipientType.
 *
 */
@SuppressWarnings("all")
@CoInterface(guid="{00000000-0000-0000-0000-000000000000}")
public class OlTaskRecipientType implements ComEnum {
  static boolean __typelib__loaded = __TypeLib.load();

  // Typed constants
  public final static OlTaskRecipientType olUpdate = new OlTaskRecipientType(2);
  public final static OlTaskRecipientType olFinalStatus = new OlTaskRecipientType(3);

  // Integer constants for bitsets and switch statements
  public final static int _olUpdate = 2;
  public final static int _olFinalStatus = 3;

  // Value, readonly field.
  public final int value;

  // Private constructor, use valueOf to create an instance.
  private OlTaskRecipientType(int value) { this.value = value; }

  // Return one of the predefined typed constants for the given value or create a new object.
  public static  OlTaskRecipientType valueOf(int value) {
    switch(value) {
    case 2: return olUpdate;
    case 3: return olFinalStatus;
    default: return new OlTaskRecipientType(value);
    }
  }

  public String toString() {
    switch(value) {
    case 2: return "olUpdate";
    case 3: return "olFinalStatus";
    default: {
      StringBuilder sbuf = new StringBuilder();
      sbuf.append("[").append(value).append("=");
      if ((value & 2) != 0) sbuf.append("|olUpdate");
      if ((value & 3) != 0) sbuf.append("|olFinalStatus");
      return sbuf.toString();
      }
    }
  }
}


text:
namespace MsgPack.Serialization
{
	/// <summary>
	///		Represents compatibility level.
	/// </summary>
	public enum SerializationCompatibilityLevel
	{
		/// <summary>
		///		Use latest feature. Almost backward compatible, but some compatibities are broken.
		/// </summary>
		Latest = 0,

		/// <summary>
		///		Compatible for version 0.5.x or former.
		/// </summary>
		Version0_5,

		/// <summary>
		///		Compatible for version 0.6.x, 0.7.x, 0.8.x, and 0.9.x.
		/// </summary>
		Version0_9
	}
}


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

namespace Orchard.BackgroundTasks
{
    /// <summary>
    /// An implementation of <see cref="IBackgroundTaskService"/> is a registered as singleton
    /// and handles the periodic execution of background tasks.
    /// </summary>
    public interface IBackgroundTaskService
    {
        /// <summary>
        /// Activates the tasks.
        /// </summary>
        void Activate();

        /// <summary>
        /// Terminates the tasks.
        /// </summary>
        void Terminate();

        /// <summary>
        /// Returns all the tasks and their current state.
        /// </summary>
        /// <returns></returns>
        IDictionary<IBackgroundTask, BackgroundTaskState> GetTasks();

        /// <summary>
        /// Sets the period of a named task group. This has no effect until <see cref="Activate"/> is called.
        /// </summary>
        void SetDelay(string group, TimeSpan period);
    }
}


text:
'use strict';

// Teams controller
angular.module('teams').controller('TeamsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Teams', '$http',
	function($scope, $stateParams, $location, Authentication, Teams, $http) {
		$scope.authentication = Authentication;

		// Create new Team
		$scope.create = function() {
			// Create new Team object
			var team = new Teams ({
				name: this.name
			});

			// Redirect after save
			team.$save(function(response) {
				$location.path('teams/' + response._id);

				// Clear form fields
				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Team
		$scope.remove = function(team) {
			if ( team ) {
				team.$remove();

				for (var i in $scope.teams) {
					if ($scope.teams [i] === team) {
						$scope.teams.splice(i, 1);
					}
				}
			} else {
				$scope.team.$remove(function() {
					$location.path('teams');
				});
			}
		};

		// Update existing Team
		$scope.update = function() {
			var team = $scope.team;
			team.$update(function() {
				$location.path('teams/' + team._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Teams
		$scope.find = function() {
			$scope.teams = Teams.query();
		};

		// Find existing Team
		$scope.findOne = function() {
			$scope.team = Teams.get({
				teamId: $stateParams.teamId
			});
		};

		// Find existing Team
		$scope.addPlayer = function() {
//                        $scope.team.players.push($scope.player);
//                        console.log($scope.team);
                        var team = $scope.team;
                        team.players.push({
                            first_name: $scope.player.first_name,
                            last_name: $scope.player.last_name,
                            jersey: $scope.player.jersey
                        });
			team.$update(function() {
				$location.path('teams/' + team._id + "/edit");
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

                $scope.remove = function(player) {
                    var team = $scope.team;
                    $http({
                        method: 'DELETE',
                        url: 'teams/' + team._id + '/player/' + player._id
                    }).success(function(response) {
                        $scope.findOne();
                    }).error(function(response) {
                        $scope
                                .error = response.message;
                    });

                }
	}
]);


text:
// Package metrics is a largely a wrapper around the standard go-kit
// Provider type, with an extension for Cardinality estimators, for use
// on large sets.
//
// It is extracted like this for convenience. See the Provider documentation
// for more information.
package metrics

import (
	"github.com/go-kit/kit/metrics"
)

// Provider represents the different types of metrics that a provider
// can expose. We duplicate the definition from go-kit for 2 reasons:
//
//  1. A little copying never hurt anyone (and in copying, we avoid the
//     need to import and vendor all of go-kit's supported providers
//  2. It provides us an extension mechanism for our own custom metric
//     types that we can implement without go-kit's approval.
type Provider interface {
	NewCounter(name string) metrics.Counter
	NewGauge(name string) metrics.Gauge
	NewHistogram(name string, buckets int) metrics.Histogram
	NewCardinalityCounter(name string) CardinalityCounter
	Stop()
}


text:
package brooklyn.management.internal;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import brooklyn.management.ExecutionManager;
import brooklyn.util.collections.MutableMap;
import brooklyn.util.exceptions.Exceptions;
import brooklyn.util.task.BasicExecutionManager;
import brooklyn.util.task.SingleThreadedScheduler;

public class AsyncCollectionChangeAdapter<Item> implements CollectionChangeListener<Item> {

    private static final Logger LOG = LoggerFactory.getLogger(AsyncCollectionChangeAdapter.class);

    private final ExecutionManager executor;
    private final CollectionChangeListener<Item> delegate;

    public AsyncCollectionChangeAdapter(ExecutionManager executor, CollectionChangeListener<Item> delegate) {
    	this.executor = checkNotNull(executor, "executor");
        this.delegate = checkNotNull(delegate, "delegate");
        ((BasicExecutionManager) executor).setTaskSchedulerForTag(delegate, SingleThreadedScheduler.class);
    }

    @Override
    public void onItemAdded(final Item item) {
    	executor.submit(MutableMap.of("tag", delegate), new Runnable() {
    		public void run() {
    			try {
    				delegate.onItemAdded(item);
    			} catch (Throwable t) {
    				LOG.warn("Error notifying listener of itemAdded("+item+")", t);
    				Exceptions.propagate(t);
    			}
    		}
    	});
    }

    @Override
    public void onItemRemoved(final Item item) {
    	executor.submit(MutableMap.of("tag", delegate), new Runnable() {
    		public void run() {
    			try {
    				delegate.onItemRemoved(item);
    			} catch (Throwable t) {
    				LOG.warn("Error notifying listener of itemAdded("+item+")", t);
    				Exceptions.propagate(t);
    			}
    		}
    	});
    }

    @Override
    public int hashCode() {
        return delegate.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return (other instanceof AsyncCollectionChangeAdapter) &&
        		delegate.equals(((AsyncCollectionChangeAdapter<?>) other).delegate);
    }
}


text:
/*----------------------------------------------------------------------
  File    : carpenter.h
  Contents: carpenter algorithm for finding frequent item sets
  Author  : Christian Borgelt
  History : 2013.10.31 file created from carpenter.c
            2014.08.23 interface of function carpenter() changed
            2014.08.28 functions carp_data() and carp_repo() added
----------------------------------------------------------------------*/
#ifndef __CARPENTER__
#define __CARPENTER__
#include "tract.h"
#include "repotree.h"
#ifndef ISR_CLOMAX
#define ISR_CLOMAX
#endif
#include "report.h"

/*----------------------------------------------------------------------
  Preprocessor Definitions
----------------------------------------------------------------------*/
/* --- evaluation measures --- */
#define CARP_NONE     0         /* no measure */
#define CARP_LDRATIO  1         /* binary log. of support quotient */

/* --- operation modes --- */
#define CARP_PERFECT  0x0010    /* prune with perfect extensions */
#define CARP_FILTER   0x0020    /* filter maximal sets with repo. */
#define CARP_MAXONLY  0x0040    /* add only maximal sets to repo. */
#define CARP_COLLATE  0x0080    /* flag for collating transactions */
#define CARP_DEFAULT  CARP_COLLATE|CARP_PERFECT
#ifdef NDEBUG
#define CARP_NOCLEAN  0x8000
#else                           /* do not clean up memory */
#define CARP_NOCLEAN  0         /* in function carpenter() */
#endif
#define CARP_VERBOSE  INT_MIN   /* verbose message output */

/* --- carpenter variants --- */
#define CARP_AUTO     0         /* auto. choice based on table size */
#define CARP_TABLE    1         /* item occurrence counter table */
#define CARP_TIDLIST  2         /* transaction identifier lists */

/*----------------------------------------------------------------------
  Functions
----------------------------------------------------------------------*/
extern int carp_data (TABAG *tabag, int target, SUPP smin, ITEM zmin,
                      int eval, int algo, int mode, int sort);
extern int carp_repo (ISREPORT *report, int target,
                      int eval, double thresh, int algo, int mode);
extern int carpenter (TABAG *tabag, int target, SUPP smin,
                      int eval, double thresh, int algo, int mode,
                      ISREPORT *report);
#endif


text:
package com.bitpay.sdk.android;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bitpay.sdk.model.Invoice;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.util.Date;
import java.util.Hashtable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class InvoiceActivity extends Activity implements NfcAdapter.CreateNdefMessageCallback, NfcAdapter.OnNdefPushCompleteCallback {

    public static final int RESULT_USER_CANCELED = 10;
    public static final int RESULT_STATE_INVALID = 11;
    public static final int RESULT_EXPIRED = 12;
    public static final int RESULT_COMPLETE = 13;
    public static final int RESULT_CONFIRMED = 14;
    public static final int RESULT_PAID = 15;
    public static final int RESULT_OVERPAID = 16;
    public static final int RESULT_PARTIALLY_PAID = 17;

    public static final Executor executor = Executors.newCachedThreadPool();

    public static final String INVOICE = "invoice";
    public static final String CLIENT = "bitpay";
    private static final String TRIGGERED_WALLET = "triggered";
    private static final long PAID_INTERVAL_MILLIS = 2000;

    private boolean triggeredWallet;

    private NfcAdapter mNfcAdapter;
    private Invoice mInvoice = null;
    private BitPayAndroid client;
    private AsyncTask<String, Invoice, Void> followInvoiceTask;
    private AsyncTask<Void, Void, Void> updateTimerTask;

    private ProgressBar progressBar;
    private ProgressBar loadingQr;
    private TextView status;
    private TextView price;

    private Button launchWallet;
    private Button refund;
    private TextView showQR;
    private ImageView qrView;

    private TextView address;
    private TextView timeRemaining;
    private TextView conversion;

    public static int getResourseIdByName(String packageName, String className, String name) {
        Class r = null;
        int id = 0;
        try {
            r = Class.forName(packageName + ".R");

            Class[] classes = r.getClasses();
            Class desireClass = null;

            for (int i = 0; i < classes.length; i++) {
                if (classes[i].getName().split("\\$")[1].equals(className)) {
                    desireClass = classes[i];

                    break;
                }
            }

            if (desireClass != null)
                id = desireClass.getField(name).getInt(desireClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        return id;

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(INVOICE, mInvoice);
        outState.putBoolean(TRIGGERED_WALLET, triggeredWallet);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setResult(RESULT_USER_CANCELED);
        setContentView(getResourseIdByName(getPackageName(), "layout", "activity_invoice"));

        status = (TextView) findViewById(getResourseIdByName(getPackageName(), "id", "status"));
        price = (TextView) findViewById(getResourseIdByName(getPackageName(), "id", "price"));
        refund = (Button) findViewById(getResourseIdByName(getPackageName(), "id", "refund"));

        launchWallet = (Button) findViewById(getResourseIdByName(getPackageName(), "id", "launchWallet"));
        progressBar = (ProgressBar) findViewById(getResourseIdByName(getPackageName(), "id", "progressBar"));
        loadingQr = (ProgressBar) findViewById(getResourseIdByName(getPackageName(), "id", "loadingQr"));
        qrView = (ImageView) findViewById(getResourseIdByName(getPackageName(), "id", "qr"));

        showQR = (TextView) findViewById(getResourseIdByName(getPackageName(), "id", "showQr"));
        address = (TextView) findViewById(getResourseIdByName(getPackageName(), "id", "address"));
        timeRemaining = (TextView) findViewById(getResourseIdByName(getPackageName(), "id", "timeRemaining"));
        conversion = (TextView) findViewById(getResourseIdByName(getPackageName(), "id", "conversion"));

        if (savedInstanceState != null) {
            mInvoice = savedInstanceState.getParcelable(INVOICE);
            client = savedInstanceState.getParcelable(CLIENT);
            triggeredWallet = savedInstanceState.getBoolean(TRIGGERED_WALLET);
        } else {
            mInvoice = getIntent().getParcelableExtra(INVOICE);
            client = getIntent().getParcelableExtra(CLIENT);
            triggeredWallet = getIntent().getBooleanExtra(TRIGGERED_WALLET, false);
        }

        progressBar.setRotation(180);
        price.setText(mInvoice.getBtcPrice() + " BTC");
        timeRemaining.setText(getRemainingTimeAsString());
        conversion.setText(mInvoice.getBtcPrice() + " BTC = " + mInvoice.getPrice() + mInvoice.getCurrency());
        address.setText(getAddress());
        address.setPaintFlags(address.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager ClipMan = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipMan.setPrimaryClip(ClipData.newPlainText("label", mInvoice.getPaymentUrls().getBIP73()));
                Toast toast = Toast.makeText(getApplicationContext(), "Copied payment address to clipboard", Toast.LENGTH_LONG);
                toast.show();
            }
        });
        showQR.setPaintFlags(showQR.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        showQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                triggerQrLoad();
            }
        });
        launchWallet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent bitcoinIntent = new Intent(Intent.ACTION_VIEW);
                bitcoinIntent.setData(Uri.parse(mInvoice.getBIP21due()));
                startActivity(bitcoinIntent);
            }
        });

        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter != null) {
            // Register callback to set NDEF message
            mNfcAdapter.setNdefPushMessageCallback(this, this);

            // Register callback to listen for message-sent success
            mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
        } else {
            Log.i("InvoiceActivity", "NFC is not available on this device");
        }
        if (!triggeredWallet) {
            if (BitPayAndroid.isWalletAvailable(this)) {
                Intent bitcoinIntent = new Intent(Intent.ACTION_VIEW);
                bitcoinIntent.setData(Uri.parse(mInvoice.getBIP21due()));
                triggeredWallet = true;
                startActivity(bitcoinIntent);
            } else {
                Toast.makeText(getApplicationContext(), "You don't have any bitcoin wallets installed.", Toast.LENGTH_LONG).show();
                triggerQrLoad();
            }
        } else {
            triggerStatusCheck();
        }
    }

    private void setupUpdateTimer() {
        updateTimerTask = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                while (true) {
                    publishProgress(null, null);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                }
            }

            @Override
            protected void onProgressUpdate(Void... values) {
                super.onProgressUpdate(values);

                int remainingSeconds = getRemainingSeconds();
                if (remainingSeconds < 0) {
                    timeRemaining.setText("-");
                    progressBar.setProgress(0);
                } else {
                    timeRemaining.setText(getRemainingTimeAsString());
                    progressBar.setProgress((getRemainingSeconds() * 100) / (15 * 60));
                }
            }
        }.executeOnExecutor(executor, null, null);
    }

    private void triggerStatusCheck() {
        if (followInvoiceTask != null) {
            followInvoiceTask.cancel(true);
        }
        if (client == null) {
            return;
        }
        followInvoiceTask = new BitPayAndroid.FollowInvoiceStatusTask(client) {
            @Override
            protected void onProgressUpdate(Invoice... values) {
                Invoice invoice = values[0];
                Invoice prev = mInvoice;
                if (invoice != null) {
                    mInvoice = invoice;
                } else {
                    return;
                }
                if (invoice.getExceptionStatus().equals("paidPartial") && !prev.getBtcDue().equals(invoice.getBtcDue())) {
                    status.setText("Partial payment received. Due amount:");
                    price.setText(invoice.getBtcDue() + " BTC");
                    InvoiceActivity.this.setResult(RESULT_PARTIALLY_PAID);
                    if (qrView.getVisibility() == View.VISIBLE) {
                        triggerQrLoad();
                    }
                    return;
                }
                if (invoice.getExceptionStatus().equals("paidOver")) {
                    InvoiceActivity.this.setResult(RESULT_OVERPAID);
                    status.setText("This invoice was overpaid.");
                    hidePaymentButtons();
                    showRefund();
                    this.cancel(true);
                    return;
                }
                super.onProgressUpdate(values);
            }

            @Override
            public void onStatePaid() {
                InvoiceActivity.this.setResult(RESULT_PAID);
                checkExceptionAndFinish();
            }

            private void checkExceptionAndFinish() {
                if (mInvoice.getExceptionStatus().equals("false")) {
                    hidePaymentButtons();
                    showReceipt();
                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected Void doInBackground(Void... params) {
                            try {
                                Thread.sleep(PAID_INTERVAL_MILLIS);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            super.onPostExecute(aVoid);

                            InvoiceActivity.this.finish();
                        }
                    }.executeOnExecutor(executor, null, null);

                    this.cancel(true);
                }
            }

            @Override
            public void onStateConfirmed() {
                InvoiceActivity.this.setResult(RESULT_CONFIRMED);
                checkExceptionAndFinish();
            }

            @Override
            public void onStateComplete() {
                InvoiceActivity.this.setResult(RESULT_COMPLETE);
                checkExceptionAndFinish();
            }

            @Override
            public void onStateExpired() {
                InvoiceActivity.this.setResult(RESULT_EXPIRED);
                checkExceptionAndFinish();
            }

            @Override
            public void onStateInvalid() {
                InvoiceActivity.this.setResult(RESULT_STATE_INVALID);
                checkExceptionAndFinish();
            }
        }.executeOnExecutor(executor, mInvoice.getId());
    }

    private void showRefund() {
        refund = (Button) findViewById(getResourseIdByName(getPackageName(), "id", "refund"));
        refund.setVisibility(View.VISIBLE);
        refund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("message/rfc822");
                intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"support@bitpay.com"});
                intent.putExtra(Intent.EXTRA_SUBJECT, "Refund Request");
                intent.putExtra(Intent.EXTRA_TEXT, "Invoice: " + mInvoice.getUrl() +
                        ((mInvoice.getRefundAddresses() != null && mInvoice.getRefundAddresses().size() > 0)
                                ? "\nRefund Address:" + mInvoice.getRefundAddresses() : "")
                        + "\nReason: Overpaid invoice");

                startActivity(Intent.createChooser(intent, "Send Email"));
            }
        });
    }

    private void showReceipt() {

        price.setVisibility(View.VISIBLE);
        price.setText(mInvoice.getBtcPrice() + " BTC paid");
        status.setText("Your payment was received successfully");
    }

    private void hidePaymentButtons() {

        progressBar.setVisibility(View.GONE);
        loadingQr.setVisibility(View.GONE);
        price.setVisibility(View.GONE);

        launchWallet.setVisibility(View.GONE);
        showQR.setVisibility(View.GONE);
        qrView.setVisibility(View.GONE);

        address.setVisibility(View.GONE);
        timeRemaining.setVisibility(View.GONE);
        conversion.setVisibility(View.GONE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (followInvoiceTask != null) {
            followInvoiceTask.cancel(true);
        }
        if (updateTimerTask != null) {
            updateTimerTask.cancel(true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        triggerStatusCheck();
        setupUpdateTimer();
    }

    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {

        if (mInvoice != null && mInvoice.getPaymentUrls() != null && mInvoice.getPaymentUrls().getBIP72b() != null) {
            return new NdefMessage(new NdefRecord[]{
                    NdefRecord.createUri(mInvoice.getPaymentUrls().getBIP72())
            });
        }
        return null;
    }

    @Override
    public void onNdefPushComplete(NfcEvent event) {
        // Pass
    }

    public int getRemainingSeconds() {
        Date now = new Date();
        int millis = (int) (Math.abs(now.getTime() - Long.parseLong(mInvoice.getExpirationTime())));
        return millis / 1000;
    }

    public String getRemainingTimeAsString() {
        int seconds = getRemainingSeconds();
        return String.format("%02d:%02d", seconds / 60, seconds % 60);
    }

    public String getAddress() {
        String bip21 = mInvoice.getPaymentUrls().getBIP21();
        return bip21.substring(bip21.indexOf(":") + 1, bip21.indexOf("?"));
    }

    public Bitmap generateQR(String text) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x * 3 / 4;
        int height = width;
        MultiFormatWriter writer = new MultiFormatWriter();
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
        BitMatrix matrix = null;
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        try {
            matrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            return bmp;
        }
        for (int x = 0; x < width; x++){
            for (int y = 0; y < height; y++){
                bmp.setPixel(x, y, matrix.get(x,y) ? Color.BLACK : Color.WHITE);
            }
        }
        return bmp;
    }

    private void triggerQrLoad() {
        new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                qrView.setVisibility(View.GONE);
                showQR.setVisibility(View.GONE);
                loadingQr.setVisibility(View.VISIBLE);
            }

            @Override
            protected Bitmap doInBackground(Void... params) {
                return generateQR(mInvoice.getBIP21due());
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                qrView.setImageBitmap(bitmap);
                loadingQr.setVisibility(View.GONE);
                showQR.setVisibility(View.GONE);
                qrView.setVisibility(View.VISIBLE);
            }
        }.executeOnExecutor(executor, null, null);
    }
}


text:
package whitelist

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"fmt"
	"io"

	"github.com/go-openapi/runtime"

	strfmt "github.com/go-openapi/strfmt"

	"github.com/codedellemc/gorackhd/models"
)

// DeleteNodesMacaddressDhcpWhitelistReader is a Reader for the DeleteNodesMacaddressDhcpWhitelist structure.
type DeleteNodesMacaddressDhcpWhitelistReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the recieved o.
func (o *DeleteNodesMacaddressDhcpWhitelistReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 204:
		result := NewDeleteNodesMacaddressDhcpWhitelistNoContent()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	case 404:
		result := NewDeleteNodesMacaddressDhcpWhitelistNotFound()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		result := NewDeleteNodesMacaddressDhcpWhitelistDefault(response.Code())
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result
	}
}

// NewDeleteNodesMacaddressDhcpWhitelistNoContent creates a DeleteNodesMacaddressDhcpWhitelistNoContent with default headers values
func NewDeleteNodesMacaddressDhcpWhitelistNoContent() *DeleteNodesMacaddressDhcpWhitelistNoContent {
	return &DeleteNodesMacaddressDhcpWhitelistNoContent{}
}

/*DeleteNodesMacaddressDhcpWhitelistNoContent handles this case with default header values.

delete completed successfully

*/
type DeleteNodesMacaddressDhcpWhitelistNoContent struct {
}

func (o *DeleteNodesMacaddressDhcpWhitelistNoContent) Error() string {
	return fmt.Sprintf("[DELETE /nodes/{macaddress}/dhcp/whitelist][%d] deleteNodesMacaddressDhcpWhitelistNoContent ", 204)
}

func (o *DeleteNodesMacaddressDhcpWhitelistNoContent) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	return nil
}

// NewDeleteNodesMacaddressDhcpWhitelistNotFound creates a DeleteNodesMacaddressDhcpWhitelistNotFound with default headers values
func NewDeleteNodesMacaddressDhcpWhitelistNotFound() *DeleteNodesMacaddressDhcpWhitelistNotFound {
	return &DeleteNodesMacaddressDhcpWhitelistNotFound{}
}

/*DeleteNodesMacaddressDhcpWhitelistNotFound handles this case with default header values.

The node with the identifier was not found

*/
type DeleteNodesMacaddressDhcpWhitelistNotFound struct {
	Payload *models.Error
}

func (o *DeleteNodesMacaddressDhcpWhitelistNotFound) Error() string {
	return fmt.Sprintf("[DELETE /nodes/{macaddress}/dhcp/whitelist][%d] deleteNodesMacaddressDhcpWhitelistNotFound  %+v", 404, o.Payload)
}

func (o *DeleteNodesMacaddressDhcpWhitelistNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.Error)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}

// NewDeleteNodesMacaddressDhcpWhitelistDefault creates a DeleteNodesMacaddressDhcpWhitelistDefault with default headers values
func NewDeleteNodesMacaddressDhcpWhitelistDefault(code int) *DeleteNodesMacaddressDhcpWhitelistDefault {
	return &DeleteNodesMacaddressDhcpWhitelistDefault{
		_statusCode: code,
	}
}

/*DeleteNodesMacaddressDhcpWhitelistDefault handles this case with default header values.

Unexpected error
*/
type DeleteNodesMacaddressDhcpWhitelistDefault struct {
	_statusCode int

	Payload *models.Error
}

// Code gets the status code for the delete nodes macaddress dhcp whitelist default response
func (o *DeleteNodesMacaddressDhcpWhitelistDefault) Code() int {
	return o._statusCode
}

func (o *DeleteNodesMacaddressDhcpWhitelistDefault) Error() string {
	return fmt.Sprintf("[DELETE /nodes/{macaddress}/dhcp/whitelist][%d] DeleteNodesMacaddressDhcpWhitelist default  %+v", o._statusCode, o.Payload)
}

func (o *DeleteNodesMacaddressDhcpWhitelistDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	o.Payload = new(models.Error)

	// response payload
	if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
		return err
	}

	return nil
}


text:
/*
 * 文件名称:          ExpertTest.java
 * 版权所有@ 2014-2016 无锡开云信息技术有限公司
 * 编译器:           JDK1.8
 * 时间:             下午4:18:35
 */
package com.ky.tao.attention;

import org.junit.Before;
import org.junit.Test;

import com.ky.tao.base.BaseCallBack;
import com.ky.tao.common.httpclient.KYRequestInfo;
import com.ky.tao.entity.DeleteInfo;
import com.ky.tao.entity.SearchInfo;

/**
 * TODO: 文件注释
 *

 *

 * Version:        V1.0.0
 *

 * 作者:           liangjinjing
 *

 * 日期:           2016年10月29日
 *

 * 负责人:         liangjinjing
 *

 *

 */
public class AttentionTest
{

    @ Before
    public void init()
    {
        if (callback == null)
        {
            callback = new BaseCallBack(AttentionTest.class);
        }
    }

    @ Test
    public void addAttention()
    {
        KYRequestInfo requestInfo = new KYRequestInfo();
        requestInfo.setUrl("http://localhost:8080/attention/add");
        requestInfo.setBodyInfo(new AddAttentionInfo());
        callback.doPost(requestInfo, true);
    }

    @ Test
    public void updateAttention()
    {
        KYRequestInfo requestInfo = new KYRequestInfo();
        requestInfo.setUrl("http://localhost:8080/attention/update");
        AddAttentionInfo addInfo = new AddAttentionInfo();
        addInfo.setId(1);
        addInfo.setDemandId(2);
        requestInfo.setBodyInfo(addInfo);
        callback.doPost(requestInfo, true);
    }

    @ Test
    public void searchAttention()
    {
        KYRequestInfo requestInfo = new KYRequestInfo();
        requestInfo.setUrl("http://localhost:8080/attention/search");
        SearchInfo searchInfo = new SearchInfo();
        searchInfo.setKeyword("小");
        requestInfo.setBodyInfo(searchInfo);
        callback.doPost(requestInfo, true);
    }

    @ Test
    public void deleteAttentions()
    {
        KYRequestInfo requestInfo = new KYRequestInfo();
        requestInfo.setUrl("http://localhost:8080/attention/delete");
        DeleteInfo deleteInfo = new DeleteInfo();
        deleteInfo.setIds(new long[]{1});
        requestInfo.setBodyInfo(deleteInfo);
        callback.doPost(requestInfo, true);
    }

    private BaseCallBack callback;
}


text:
require "fileutils"
require "shellwords"
require_relative "../../../synced_folders/unix_mount_helpers"

module VagrantPlugins
  module GuestLinux
    module Cap
      class MountSMBSharedFolder

        extend SyncedFolder::UnixMountHelpers

        # Mounts and SMB folder on linux guest
        #
        # @param [Machine] machine
        # @param [String] name of mount
        # @param [String] path of mount on guest
        # @param [Hash] hash of mount options
        def self.mount_smb_shared_folder(machine, name, guestpath, options)
          expanded_guest_path = machine.guest.capability(
            :shell_expand_guest_path, guestpath)
          options[:smb_id] ||= name

          mount_device = options[:plugin].capability(:mount_name, options)
          mount_options, _, _ = options[:plugin].capability(
            :mount_options, name, expanded_guest_path, options)
          mount_type = options[:plugin].capability(:mount_type)
          # If a domain is provided in the username, separate it
          username, domain = (options[:smb_username] || '').split('@', 2)
          smb_password = options[:smb_password]
          # Ensure password is scrubbed
          Vagrant::Util::CredentialScrubber.sensitive(smb_password)

          if mount_options.include?("mfsymlinks")
            display_mfsymlinks_warning(machine.env)
          end

          mount_command = "mount -t #{mount_type} -o #{mount_options} #{mount_device} #{expanded_guest_path}"

          # Create the guest path if it doesn't exist
          machine.communicate.sudo("mkdir -p #{expanded_guest_path}")

          # Write the credentials file
          machine.communicate.sudo(<<-SCRIPT)
cat <<"EOF" >/etc/smb_creds_#{name}
username=#{username}
password=#{smb_password}
#{domain ? "domain=#{domain}" : ""}
EOF
chmod 0600 /etc/smb_creds_#{name}
SCRIPT

          # Attempt to mount the folder. We retry here a few times because
          # it can fail early on.
          begin
            retryable(on: Vagrant::Errors::LinuxMountFailed, tries: 10, sleep: 2) do
              no_such_device = false
              stderr = ""
              status = machine.communicate.sudo(mount_command, error_check: false) do |type, data|
                if type == :stderr
                  no_such_device = true if data =~ /No such device/i
                  stderr += data.to_s
                end
              end
              if status != 0 || no_such_device
                raise Vagrant::Errors::LinuxMountFailed,
                  command: mount_command,
                  output: stderr
              end
            end
          ensure
            # Always remove credentials file after mounting attempts
            # have been completed
            if !machine.config.vm.allow_fstab_modification
              machine.communicate.sudo("rm /etc/smb_creds_#{name}")
            end
          end

          emit_upstart_notification(machine, expanded_guest_path)
        end

        def self.display_mfsymlinks_warning(env)
          d_file = env.data_dir.join("mfsymlinks_warning")
          if !d_file.exist?
            FileUtils.touch(d_file.to_path)
            env.ui.warn(I18n.t("vagrant.actions.vm.smb.mfsymlink_warning"))
          end
        end
      end
    end
  end
end


text: MongoPeople::Application.config.session_store :cookie_store, key: '_mongo-people_session'


text:
<?php

namespace Symfony\Component\Security\Acl\Domain;

use Doctrine\Common\Cache\Cache;
use Symfony\Component\Security\Acl\Model\AclCacheInterface;
use Symfony\Component\Security\Acl\Model\AclInterface;
use Symfony\Component\Security\Acl\Model\ObjectIdentityInterface;
use Symfony\Component\Security\Acl\Model\PermissionGrantingStrategyInterface;

/**
 * This class is a wrapper around the actual cache implementation.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class DoctrineAclCache implements AclCacheInterface {
	const PREFIX = 'sf2_acl_';

	private $cache;
	private $prefix;
	private $permissionGrantingStrategy;

	/**
	 * Constructor
	 *
	 * @param Cache                               $cache
	 * @param PermissionGrantingStrategyInterface $permissionGrantingStrategy
	 * @param string                              $prefix
	 *
	 * @return void
	 */
	public function __construct(Cache $cache, PermissionGrantingStrategyInterface $permissionGrantingStrategy, $prefix = self::PREFIX) {
		if (0 === strlen($prefix)) {
			throw new \InvalidArgumentException('$prefix cannot be empty.');
		}

		$this->cache = $cache;
		$this->permissionGrantingStrategy = $permissionGrantingStrategy;
		$this->prefix = $prefix;
	}

	/**
	 * {@inheritDoc}
	 */
	public function clearCache() {
		$this->cache->deleteByPrefix($this->prefix);
	}

	/**
	 * {@inheritDoc}
	 */
	public function evictFromCacheById($aclId) {
		$lookupKey = $this->getAliasKeyForIdentity($aclId);
		if (!$this->cache->contains($lookupKey)) {
			return;
		}

		$key = $this->cache->fetch($lookupKey);
		if ($this->cache->contains($key)) {
			$this->cache->delete($key);
		}

		$this->cache->delete($lookupKey);
	}

	/**
	 * {@inheritDoc}
	 */
	public function evictFromCacheByIdentity(ObjectIdentityInterface $oid) {
		$key = $this->getDataKeyByIdentity($oid);
		if (!$this->cache->contains($key)) {
			return;
		}

		$this->cache->delete($key);
	}

	/**
	 * {@inheritDoc}
	 */
	public function getFromCacheById($aclId) {
		$lookupKey = $this->getAliasKeyForIdentity($aclId);
		if (!$this->cache->contains($lookupKey)) {
			return null;
		}

		$key = $this->cache->fetch($lookupKey);
		if (!$this->cache->contains($key)) {
			$this->cache->delete($lookupKey);

			return null;
		}

		return $this->unserializeAcl($this->cache->fetch($key));
	}

	/**
	 * {@inheritDoc}
	 */
	public function getFromCacheByIdentity(ObjectIdentityInterface $oid) {
		$key = $this->getDataKeyByIdentity($oid);
		if (!$this->cache->contains($key)) {
			return null;
		}

		return $this->unserializeAcl($this->cache->fetch($key));
	}

	/**
	 * {@inheritDoc}
	 */
	public function putInCache(AclInterface $acl) {
		if (null === $acl->getId()) {
			throw new \InvalidArgumentException('Transient ACLs cannot be cached.');
		}

		if (null !== $parentAcl = $acl->getParentAcl()) {
			$this->putInCache($parentAcl);
		}

		$key = $this->getDataKeyByIdentity($acl->getObjectIdentity());
		$this->cache->save($key, serialize($acl));
		$this->cache->save($this->getAliasKeyForIdentity($acl->getId()), $key);
	}

	/**
	 * Unserializes the ACL.
	 *
	 * @param string $serialized
	 * @return AclInterface
	 */
	private function unserializeAcl($serialized) {
		$acl = unserialize($serialized);

		if (null !== $parentId = $acl->getParentAcl()) {
			$parentAcl = $this->getFromCacheById($parentId);

			if (null === $parentAcl) {
				return null;
			}

			$acl->setParentAcl($parentAcl);
		}

		$reflectionProperty = new \ReflectionProperty($acl, 'permissionGrantingStrategy');
		$reflectionProperty->setAccessible(true);
		$reflectionProperty->setValue($acl, $this->permissionGrantingStrategy);
		$reflectionProperty->setAccessible(false);

		$aceAclProperty = new \ReflectionProperty('Symfony\Component\Security\Acl\Domain\Entry', 'acl');
		$aceAclProperty->setAccessible(true);

		foreach ($acl->getObjectAces() as $ace) {
			$aceAclProperty->setValue($ace, $acl);
		}
		foreach ($acl->getClassAces() as $ace) {
			$aceAclProperty->setValue($ace, $acl);
		}

		$aceClassFieldProperty = new \ReflectionProperty($acl, 'classFieldAces');
		$aceClassFieldProperty->setAccessible(true);
		foreach ($aceClassFieldProperty->getValue($acl) as $aces) {
			foreach ($aces as $ace) {
				$aceAclProperty->setValue($ace, $acl);
			}
		}
		$aceClassFieldProperty->setAccessible(false);

		$aceObjectFieldProperty = new \ReflectionProperty($acl, 'objectFieldAces');
		$aceObjectFieldProperty->setAccessible(true);
		foreach ($aceObjectFieldProperty->getValue($acl) as $aces) {
			foreach ($aces as $ace) {
				$aceAclProperty->setValue($ace, $acl);
			}
		}
		$aceObjectFieldProperty->setAccessible(false);

		$aceAclProperty->setAccessible(false);

		return $acl;
	}

	/**
	 * Returns the key for the object identity
	 *
	 * @param ObjectIdentityInterface $oid
	 * @return string
	 */
	private function getDataKeyByIdentity(ObjectIdentityInterface $oid) {
		return $this->prefix . md5($oid->getType()) . sha1($oid->getType()) . '_' . md5($oid->getIdentifier()) . sha1($oid->getIdentifier());
	}

	/**
	 * Returns the alias key for the object identity key
	 *
	 * @param string $aclId
	 * @return string
	 */
	private function getAliasKeyForIdentity($aclId) {
		return $this->prefix . $aclId;
	}
}


text:
using System;
using System.IO;

namespace SMLogging
{
    /// <summary>
    /// Represents a stream that can locked for writing to a file.
    /// </summary>
    public sealed class FileLockStream : Stream
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="FileLockStream" /> class.
        /// </summary>
        /// <param name="lockHandler">The lock handler.</param>
        /// <exception cref="ArgumentNullException">Throw if <paramref name="lockHandler"/> is null.</exception>
        public FileLockStream(FileLockHandlerBase lockHandler)
        {
            if (lockHandler == null) throw new ArgumentNullException("lockHandler");

            _lockHandler = lockHandler;
        }

        /// <summary>
        /// Gets a value indicating whether this instance has a lock.
        /// </summary>
        public bool HasLock
        {
            get { return _innerStream != null; }
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports reading.
        /// </summary>
        public override bool CanRead
        {
            get { return false; }
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports seeking.
        /// </summary>
        public override bool CanSeek
        {
            get { return _innerStream.CanSeek; }
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports writing.
        /// </summary>
        public override bool CanWrite
        {
            get { return _innerStream.CanWrite; }
        }

        /// <summary>
        /// Gets the length in bytes of the stream.
        /// </summary>
        public override long Length
        {
            get { return _innerStream.Length; }
        }

        /// <summary>
        /// Gets or sets the position within the current stream.
        /// </summary>
        public override long Position
        {
            get { return _innerStream.Position; }
            set { _innerStream.Position = value; }
        }

        /// <summary>
        /// Begins an asynchronous read operation.
        /// </summary>
        /// <param name="buffer">The buffer to read the data into.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer" /> at which to begin writing data read from the stream.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param>
        /// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
        /// <returns>An <see cref="IAsyncResult" /> that represents the asynchronous read, which could still be pending.</returns>
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            var result = _innerStream.BeginRead(buffer, offset, count, callback, state);
            _totalRead = EndRead(result);
            return result;
        }

        /// <summary>
        /// Waits for the pending asynchronous read to complete.
        /// </summary>
        /// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
        /// <returns>
        /// The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams return zero (0) only at
        ///  the end of the stream, otherwise, they should block until at least one byte is available.
        /// </returns>
        public override int EndRead(IAsyncResult asyncResult)
        {
            return _totalRead;
        }

        /// <summary>
        /// Begins an asynchronous write operation.
        /// </summary>
        /// <param name="buffer">The buffer to write data from.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer" /> from which to begin writing.</param>
        /// <param name="count">The maximum number of bytes to write.</param>
        /// <param name="callback">An optional asynchronous callback, to be called when the write is complete.</param>
        /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
        /// <returns>An <see cref="IAsyncResult" /> that represents the asynchronous write, which could still be pending.</returns>
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            var result = _innerStream.BeginWrite(buffer, offset, count, callback, state);
            EndWrite(result);
            return result;
        }

        /// <summary>
        /// Ends an asynchronous write operation.
        /// </summary>
        /// <param name="asyncResult">A reference to the outstanding asynchronous I/O request.</param>
        public override void EndWrite(IAsyncResult asyncResult)
        {
        }

        /// <summary>
        /// Closes the current stream and releases any resources associated with the current stream.
        /// </summary>
        public override void Close()
        {
            _lockHandler.CloseFile();
        }

        /// <summary>
        /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
        /// </summary>
        public override void Flush()
        {
            _innerStream.Flush();
        }

        /// <summary>
        /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <param name="buffer">
        /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset" />
        /// and (<paramref name="offset" /> + <paramref name="count" /> - 1) replaced by the bytes read from the current source.
        /// </param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin storing the data read from the current stream.</param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns>
        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently
        /// available, or zero (0) if the end of the stream has been reached.
        /// </returns>
        public override int Read(byte[] buffer, int offset, int count)
        {
            return _innerStream.Read(buffer, offset, count);
        }

        /// <summary>
        /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
        /// </summary>
        /// <returns>The unsigned byte cast to an integer, or -1 if at the end of the stream.</returns>
        public override int ReadByte()
        {
            return _innerStream.ReadByte();
        }

        /// <summary>
        /// Sets the position within the current stream.
        /// </summary>
        /// <param name="offset">A byte offset relative to the <paramref name="origin" /> parameter.</param>
        /// <param name="origin">A value of type <see cref="SeekOrigin" /> indicating the reference point used to obtain the new position.</param>
        /// <returns>The new position within the current stream.</returns>
        public override long Seek(long offset, SeekOrigin origin)
        {
            return _innerStream.Seek(offset, origin);
        }

        /// <summary>
        /// Sets the length of the current stream.
        /// </summary>
        /// <param name="value">The desired length of the current stream in bytes.</param>
        public override void SetLength(long value)
        {
            _innerStream.SetLength(value);
        }

        /// <summary>
        /// Writes a byte to the current position in the stream and advances the position within the stream by one byte.
        /// </summary>
        /// <param name="value">The byte to write to the stream.</param>
        public override void WriteByte(byte value)
        {
            _innerStream.WriteByte(value);
        }

        /// <summary>
        /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
        /// </summary>
        /// <param name="buffer">An array of bytes. This method copies <paramref name="count" /> bytes from <paramref name="buffer" /> to the current stream.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin copying bytes to the current stream.</param>
        /// <param name="count">The number of bytes to be written to the current stream.</param>
        public override void Write(byte[] buffer, int offset, int count)
        {
            _innerStream.Write(buffer, offset, count);
        }

        /// <summary>
        /// Acquires the lock on the file.
        /// </summary>
        /// <returns><c>true</c> if a lock was acquired successfully.</returns>
        public bool AcquireLock()
        {
            var result = false;
            lock (_lock)
            {
                if (_lockLevel == 0)
                {
                    _innerStream = _lockHandler.AcquireLock();
                }
                if (_innerStream != null)
                {
                    _lockLevel++;
                    result = true;
                }
            }
            return result;
        }

        /// <summary>
        /// Releases the lock.
        /// </summary>
        public void ReleaseLock()
        {
            lock (_lock)
            {
                _lockLevel--;
                if (_lockLevel == 0)
                {
                    _lockHandler.ReleaseLock();
                    _innerStream = null;
                }
            }
        }

        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="Stream" /> and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            Close();

            base.Dispose(disposing);
        }

        private Stream _innerStream = null;
        private readonly FileLockHandlerBase _lockHandler = null;
        private int _totalRead = -1;
        private int _lockLevel = 0;
        private readonly object _lock = new object();
    }
}


text:
<!doctype html>

		<meta charset='utf-8' />
		<meta name='viewport' content='width=device-width' />
		<meta http-equiv='X-UA-Compatible' content='ie=edge'>
		<title>Your time on earth in your macOS menu bar</title>
		<link rel='stylesheet' href='/public/css/xbar.css?cb=08%20Mar%2021%2015%3a22%20GMT'>
		<link rel='preconnect' href='https://fonts.gstatic.com'>
		<link rel='preconnect' href='https://fonts.googleapis.com'>
		<link rel='stylesheet' href='https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@500&display=swap'>

	<meta name='description' content='Displays the time you are already living. - install xbar for free to get started.'>
	<meta name='author' content='Tim Regener'>
	<meta name='keywords' content='macos,menubar,xbar,bitbar'>
	<meta itemprop='image' content='http://i.imgur.com/EzUARsL.png'>
	<meta itemprop='name' content='Your time on earth in your macOS menu bar'>
	<meta itemprop='description' content='Displays the time you are already living. - install xbar for free to get started.'>
	<meta name='twitter:card' content='summary_large_image'>
	<meta name='twitter:title' content='Your time on earth in your macOS menu bar'>
	<meta name='twitter:description' content='Displays the time you are already living. - install xbar for free to get started.'>
	<meta name='twitter:image' content='http://i.imgur.com/EzUARsL.png'>
	<meta name='twitter:creator' content='matryer'>
	<meta property='og:title' content='Your time on earth in your macOS menu bar'>
	<meta property='og:description' content='Displays the time you are already living. - install xbar for free to get started.'>
	<meta property='og:url' content='https://xbarapp.com/plugins/Lifestyle/time_on_earth.10m.rb.html'>
	<meta property='og:site_name' content='xbar lets you put anything into your macOS menu bar'>
	<meta property='og:type' content='article'>
	<meta property='og:image' content='http://i.imgur.com/EzUARsL.png'>
	<link rel='apple-touch-icon' sizes='180x180' href='http://i.imgur.com/EzUARsL.png'>
	<link rel='icon' type='image/png' sizes='32x32' href='http://i.imgur.com/EzUARsL.png'>
	<link rel='shortcut icon' href='http://i.imgur.com/EzUARsL.png'>
	<meta name='msapplication-TileColor' content='#ffffff'>
	<meta name='msapplication-config' content='/public/browserconfig.xml'>
	<meta name='theme-color' content='#ffffff'>

						xbar

						💜 Sponsor

						Coming soon

					AWS

					Cryptocurrency

					Dev

					E-Commerce

					Email

					Environment

					Finance

					Games

					IoT

					Lifestyle

					Music

					Network

					Politics

					Science

					Sports

					System

					Time

					Tools

					Travel

					Weather

					Web

Your time on earth

										Tim Regener (@timlapluie on GitHub)

						Displays the time you are already living.

						🖥 Open in xbar app

Requires xbar app

							time_on_earth.10m.rb

						Edit

						Open on GitHub

#!/usr/bin/env ruby

# <bitbar.title>Your time on earth</bitbar.title>
# <bitbar.version>v1.0</bitbar.version>
# <bitbar.author>Tim Regener</bitbar.author>
# <bitbar.author.github>timlapluie</bitbar.author.github>
# <bitbar.desc>Displays the time you are already living.</bitbar.desc>
# <bitbar.image>http://i.imgur.com/EzUARsL.png</bitbar.image>
# <bitbar.dependencies>ruby</bitbar.dependencies>

# --------------------- #
# EDIT THESE VARIABLES. #
# --------------------- #

# Add your Birthday here
# Format: 'YYYY-MM-DD [hh:mm (optional)] [UTC Offset (optional)]'
BIRTHDAY = '1988-01-12 11:42 +01:00'

# -------------------------------------------------------- #
# DON'T EDIT BELOW HERE UNLESS YOU KNOW WHAT YOU'RE DOING. #
# -------------------------------------------------------- #
require 'date'

birth_time = DateTime.parse(BIRTHDAY)
time_now = DateTime.now
delta = time_now - birth_time

days = delta.to_i

hours = (delta * 24)
minutes = (hours % 1) * 60
seconds = (minutes % 1) * 60

def format_int(number)
  number.to_i.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
end

puts "#{format_int(days)} days on 🌍"
puts '---'
puts "Impressive! That's #{format_int(hours)} hours, #{format_int(minutes)} minutes, #{format_int(seconds)} seconds."

						GitHub project
						•
						Writing plugins guide

						Copyright ©2021 Mat Ryer + contributors • @matryer

						Last updated on 08 Mar 21 15:22 GMT


text:
package org.sejda.io;

import org.sejda.commons.util.IOUtils;

import java.io.IOException;
import java.nio.ByteBuffer;

import static org.sejda.commons.util.RequireUtils.requireArg;
import static org.sejda.commons.util.RequireUtils.requireNotNullArg;

/**
 * {@link SeekableSource} wrapping an existing one and providing buffered read. When a read method is called, a {@link SeekableSources#INPUT_BUFFER_SIZE_PROPERTY} long chunk of
 * bytes is read from the underlying source and stored in memory. Subsequent reads are served from the in memory buffer until they fall outside its range, at that point a new
 * buffer is read from the wrapped source.
 *
 * @author Andrea Vacondio
 */
public class BufferedSeekableSource implements SeekableSource {

    private final ByteBuffer buffer = ByteBuffer.allocate(
            Integer.getInteger(SeekableSources.INPUT_BUFFER_SIZE_PROPERTY, 8192));
    private final SeekableSource wrapped;
    private long position;
    private final long size;

    public BufferedSeekableSource(SeekableSource wrapped) {
        requireNotNullArg(wrapped, "Input decorated SeekableSource cannot be null");
        this.wrapped = wrapped;
        this.size = wrapped.size();
        this.buffer.limit(0);
    }

    @Override
    public boolean isOpen() {
        return this.wrapped.isOpen();
    }

    @Override
    public void requireOpen() throws IOException {
        this.wrapped.requireOpen();
    }

    /**
     * @return the unique id for this source
     */
    @Override
    public String id() {
        return this.wrapped.id();
    }

    @Override
    public long position() {
        return this.position;
    }

    @Override
    public SeekableSource position(long newPosition) throws IOException {
        requireArg(newPosition >= 0, "Cannot set position to a negative value");
        if (newPosition != this.position) {
            long newBufPosition = newPosition - position + buffer.position();
            if (newBufPosition >= 0 && newBufPosition < buffer.limit()) {
                buffer.position((int) newBufPosition);
            } else {
                buffer.limit(0);
                wrapped.position(newPosition);
            }
            this.position = Math.min(newPosition, size);
        }
        return this;
    }

    @Override
    public long size() {
        return size;
    }

    @Override
    public void close() throws IOException {
        IOUtils.close(wrapped);
        buffer.clear();
        buffer.limit(0);
    }

    @Override
    public int read(ByteBuffer dst) throws IOException {
        requireOpen();
        buffer.limit(0);
        wrapped.position(position);
        int read = wrapped.read(dst);
        if (read > 0) {
            position += read;
        }
        return read;
    }

    @Override
    public int read() throws IOException {
        requireOpen();
        if (ensureBuffer() > 0) {
            position++;
            return buffer.get() & 0xff;
        }
        return -1;
    }

    private int ensureBuffer() throws IOException {
        if (!buffer.hasRemaining()) {
            buffer.clear();
            wrapped.read(buffer);
            buffer.flip();
        }
        return buffer.remaining();
    }

    protected SeekableSource wrapped() {
        return wrapped;
    }

    @Override
    public SeekableSource view(long startingPosition, long length) throws IOException {
        requireOpen();
        return new BufferedSeekableSource(wrapped.view(startingPosition, length));
    }
}


text:
<?php

namespace App\Settings;

use Cake\Cache\Cache;
use Cake\Core\Configure\ConfigEngineInterface;
use Cake\Database\Exception;
use Cake\ORM\TableRegistry;
use Cake\Utility\Hash;
use RuntimeException;

class DbConfig implements ConfigEngineInterface
{

    private $scope;
    private $context;

    /**
     * Set DbConfig to return user settings as default
     * @param string $scope   User, App, (Os, Env ...)
     * @param string $context depent on the scope, the context can be uuid, string, integer, etc.
     */
    public function __construct(string $scope = 'app', string $context = 'app')
    {
        $this->scope = $scope;
        $this->context = $context;
    }

    /**
     * @param string $key Table name with the settings
     * @return array
     */
    public function read($key)
    {
        $query = TableRegistry::getTableLocator()->get($key);
        $cacheKey = $this->scope . '_' . $this->context;
        $config = Cache::read($cacheKey, 'settings');

        if ($config !== false) {
            return $config;
        }

        try {
            $items = $query->find('list', ['keyField' => 'key', 'valueField' => 'value'])
                          ->where(['scope' => $this->scope, 'context' => $this->context])
                          ->toArray();
            $items = $this->decode($items);
        } catch (Exception $e) {
            return [];
        }

        $config = Hash::expand($items);
        Cache::write($cacheKey, $config, 'settings');

        return $config;
    }

    /**
     * @param string $key Table name
     * @param array $data Data to dump.
     * @return bool
     * @throws \Exception
     */
    public function dump($key, array $data): bool
    {
        if ($key || $data) {
            throw new RuntimeException('Not implemented');
        }

        return false;
    }

    /**
     * Attempts to JSON decode each one of the provided items.
     *
     * @param array[] $items Items to be decoded
     * @return array[]
     */
    private function decode(array $items): array
    {
        foreach ($items as $key => $val) {
            $decoded = json_decode($val, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                continue;
            }

            $items[$key] = $decoded;
        }

        return $items;
    }
}