text:
//------------------------------------------------------------------------------
// <auto-generated>
//     Ce code a été généré par un outil.
//     Version du runtime :4.0.30319.18444
//
//     Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
//     le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Lobby.UserService {
    using System.Runtime.Serialization;
    using System;

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Name="CreateUserInfo", Namespace="http://schemas.datacontract.org/2004/07/LibrairieService.Models")]
    [System.SerializableAttribute()]
    public partial class CreateUserInfo : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;

        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string EmailField;

        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string PasswordField;

        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string UsernameField;

        [global::System.ComponentModel.BrowsableAttribute(false)]
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
            get {
                return this.extensionDataField;
            }
            set {
                this.extensionDataField = value;
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Email {
            get {
                return this.EmailField;
            }
            set {
                if ((object.ReferenceEquals(this.EmailField, value) != true)) {
                    this.EmailField = value;
                    this.RaisePropertyChanged("Email");
                }
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Password {
            get {
                return this.PasswordField;
            }
            set {
                if ((object.ReferenceEquals(this.PasswordField, value) != true)) {
                    this.PasswordField = value;
                    this.RaisePropertyChanged("Password");
                }
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Username {
            get {
                return this.UsernameField;
            }
            set {
                if ((object.ReferenceEquals(this.UsernameField, value) != true)) {
                    this.UsernameField = value;
                    this.RaisePropertyChanged("Username");
                }
            }
        }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName) {
            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if ((propertyChanged != null)) {
                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Name="UserMessage", Namespace="http://schemas.datacontract.org/2004/07/LibrairieService.Models")]
    [System.SerializableAttribute()]
    public partial class UserMessage : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

        [System.NonSerializedAttribute()]
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;

        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string ContentField;

        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private System.DateTime DateField;

        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string UsernameField;

        [global::System.ComponentModel.BrowsableAttribute(false)]
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
            get {
                return this.extensionDataField;
            }
            set {
                this.extensionDataField = value;
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Content {
            get {
                return this.ContentField;
            }
            set {
                if ((object.ReferenceEquals(this.ContentField, value) != true)) {
                    this.ContentField = value;
                    this.RaisePropertyChanged("Content");
                }
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public System.DateTime Date {
            get {
                return this.DateField;
            }
            set {
                if ((this.DateField.Equals(value) != true)) {
                    this.DateField = value;
                    this.RaisePropertyChanged("Date");
                }
            }
        }

        [System.Runtime.Serialization.DataMemberAttribute()]
        public string Username {
            get {
                return this.UsernameField;
            }
            set {
                if ((object.ReferenceEquals(this.UsernameField, value) != true)) {
                    this.UsernameField = value;
                    this.RaisePropertyChanged("Username");
                }
            }
        }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged(string propertyName) {
            System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
            if ((propertyChanged != null)) {
                propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="UserService.IUserService")]
    public interface IUserService {

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IUserService/CreateUser", ReplyAction="http://tempuri.org/IUserService/CreateUserResponse")]
        bool CreateUser(Lobby.UserService.CreateUserInfo info);

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IUserService/Login", ReplyAction="http://tempuri.org/IUserService/LoginResponse")]
        System.Nullable<System.Guid> Login(string username, string password);

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IUserService/Heartbeat", ReplyAction="http://tempuri.org/IUserService/HeartbeatResponse")]
        bool Heartbeat(System.Guid userToken);

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IUserService/SendGlobalMessage", ReplyAction="http://tempuri.org/IUserService/SendGlobalMessageResponse")]
        bool SendGlobalMessage(System.Guid player, string message);

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IUserService/GetGlobalMessages", ReplyAction="http://tempuri.org/IUserService/GetGlobalMessagesResponse")]
        System.Collections.Generic.List<Lobby.UserService.UserMessage> GetGlobalMessages(int limit);
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    public interface IUserServiceChannel : Lobby.UserService.IUserService, System.ServiceModel.IClientChannel {
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    public partial class UserServiceClient : System.ServiceModel.ClientBase<Lobby.UserService.IUserService>, Lobby.UserService.IUserService {

        public UserServiceClient() {
        }

        public UserServiceClient(string endpointConfigurationName) :
                base(endpointConfigurationName) {
        }

        public UserServiceClient(string endpointConfigurationName, string remoteAddress) :
                base(endpointConfigurationName, remoteAddress) {
        }

        public UserServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
                base(endpointConfigurationName, remoteAddress) {
        }

        public UserServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
                base(binding, remoteAddress) {
        }

        public bool CreateUser(Lobby.UserService.CreateUserInfo info) {
            return base.Channel.CreateUser(info);
        }

        public System.Nullable<System.Guid> Login(string username, string password) {
            return base.Channel.Login(username, password);
        }

        public bool Heartbeat(System.Guid userToken) {
            return base.Channel.Heartbeat(userToken);
        }

        public bool SendGlobalMessage(System.Guid player, string message) {
            return base.Channel.SendGlobalMessage(player, message);
        }

        public System.Collections.Generic.List<Lobby.UserService.UserMessage> GetGlobalMessages(int limit) {
            return base.Channel.GetGlobalMessages(limit);
        }
    }
}


text:
using System;
using System.Reflection;
using System.Reflection.Emit;

public static partial class Extensions
{
    /// <summary>
    ///     Pops a reference from the evaluation stack, and pushes the value type object if the object is a boxed value type,
    ///     or a reference of the given type if the object is a reference type and is an instance of that type
    /// </summary>
    /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
    /// <param name="type">The type to unbox to</param>
    public static ILGenerator UnboxAny(this ILGenerator il, Type type)
    {
        if (il == null)
            throw new ArgumentNullException(nameof(il));
        if (type == null)
            throw new ArgumentNullException(nameof(type));
#if NetCore
        var reflectingType = type.GetTypeInfo();
#else
        var reflectingType = type;
#endif
        return reflectingType.IsValueType ? il.Unbox_Any(reflectingType) : il.Castclass(reflectingType);
    }

    /// <summary>
    ///     Pops a reference from the evaluation stack, and pushes the value type object if the object is a boxed value type,
    ///     or a reference of the given type if the object is a reference type and is an instance of that type
    /// </summary>
    /// <typeparam name="T">The type to unbox to</typeparam>
    /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
    public static ILGenerator UnboxAny<T>(this ILGenerator il) => il.UnboxAny(typeof(T));

#if Net45 || NetCore
    /// <summary>
    ///     Pops a reference from the evaluation stack, and pushes the value type object if the object is a boxed value type,
    ///     or a reference of the given type if the object is a reference type and is an instance of that type
    /// </summary>
    /// <param name="il">The <see cref="T:System.Reflection.Emit.ILGenerator" /> to emit instructions from</param>
    /// <param name="type">The type to unbox to</param>
    public static ILGenerator UnboxAny(this ILGenerator il, TypeInfo type) => il.UnboxAny(type?.AsType());
#endif
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.beam.runners.portability;

import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.beam.model.jobmanagement.v1.JobApi;
import org.apache.beam.model.jobmanagement.v1.JobApi.CancelJobRequest;
import org.apache.beam.model.jobmanagement.v1.JobApi.CancelJobResponse;
import org.apache.beam.model.jobmanagement.v1.JobApi.GetJobStateRequest;
import org.apache.beam.model.jobmanagement.v1.JobApi.JobMessage;
import org.apache.beam.model.jobmanagement.v1.JobApi.JobMessagesRequest;
import org.apache.beam.model.jobmanagement.v1.JobApi.JobMessagesResponse;
import org.apache.beam.model.jobmanagement.v1.JobApi.JobStateEvent;
import org.apache.beam.model.jobmanagement.v1.JobServiceGrpc.JobServiceBlockingStub;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.metrics.MetricResults;
import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"keyfor", "nullness"}) // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
class JobServicePipelineResult implements PipelineResult, AutoCloseable {

  private static final long POLL_INTERVAL_MS = 3_000;

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

  private final ByteString jobId;
  private final int jobServerTimeout;
  private final CloseableResource<JobServiceBlockingStub> jobService;
  private @Nullable State terminalState;
  private final @Nullable Runnable cleanup;
  private org.apache.beam.model.jobmanagement.v1.JobApi.MetricResults jobMetrics;

  JobServicePipelineResult(
      ByteString jobId,
      int jobServerTimeout,
      CloseableResource<JobServiceBlockingStub> jobService,
      Runnable cleanup) {
    this.jobId = jobId;
    this.jobServerTimeout = jobServerTimeout;
    this.jobService = jobService;
    this.terminalState = null;
    this.cleanup = cleanup;
  }

  @Override
  public State getState() {
    if (terminalState != null) {
      return terminalState;
    }
    JobServiceBlockingStub stub =
        jobService.get().withDeadlineAfter(jobServerTimeout, TimeUnit.SECONDS);
    JobStateEvent response =
        stub.getState(GetJobStateRequest.newBuilder().setJobIdBytes(jobId).build());
    return getJavaState(response.getState());
  }

  @Override
  public State cancel() {
    JobServiceBlockingStub stub = jobService.get();
    CancelJobResponse response =
        stub.cancel(CancelJobRequest.newBuilder().setJobIdBytes(jobId).build());
    return getJavaState(response.getState());
  }

  @Nullable
  @Override
  public State waitUntilFinish(Duration duration) {
    if (duration.compareTo(Duration.millis(1)) <= 0) {
      // Equivalent to infinite timeout.
      return waitUntilFinish();
    } else {
      CompletableFuture<State> result = CompletableFuture.supplyAsync(this::waitUntilFinish);
      try {
        return result.get(duration.getMillis(), TimeUnit.MILLISECONDS);
      } catch (TimeoutException e) {
        // Null result indicates a timeout.
        return null;
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
      } catch (ExecutionException e) {
        throw new RuntimeException(e);
      }
    }
  }

  @Override
  public State waitUntilFinish() {
    if (terminalState != null) {
      return terminalState;
    }
    try {
      waitForTerminalState();
      propagateErrors();
      return terminalState;
    } finally {
      close();
    }
  }

  @Override
  public MetricResults metrics() {
    return PortableMetrics.of(jobMetrics);
  }

  @Override
  public void close() {
    try (CloseableResource<JobServiceBlockingStub> jobService = this.jobService) {
      JobApi.GetJobMetricsRequest metricsRequest =
          JobApi.GetJobMetricsRequest.newBuilder().setJobIdBytes(jobId).build();
      jobMetrics = jobService.get().getJobMetrics(metricsRequest).getMetrics();
      if (cleanup != null) {
        cleanup.run();
      }
    } catch (Exception e) {
      LOG.warn("Error cleaning up job service", e);
    }
  }

  private void waitForTerminalState() {
    JobServiceBlockingStub stub =
        jobService.get().withDeadlineAfter(jobServerTimeout, TimeUnit.SECONDS);
    GetJobStateRequest request = GetJobStateRequest.newBuilder().setJobIdBytes(jobId).build();
    JobStateEvent response = stub.getState(request);
    State lastState = getJavaState(response.getState());
    while (!lastState.isTerminal()) {
      try {
        Thread.sleep(POLL_INTERVAL_MS);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
      }
      response = stub.withDeadlineAfter(jobServerTimeout, TimeUnit.SECONDS).getState(request);
      lastState = getJavaState(response.getState());
    }
    terminalState = lastState;
  }

  private void propagateErrors() {
    if (terminalState != State.DONE) {
      JobMessagesRequest messageStreamRequest =
          JobMessagesRequest.newBuilder().setJobIdBytes(jobId).build();
      Iterator<JobMessagesResponse> messageStreamIterator =
          jobService
              .get()
              .withDeadlineAfter(jobServerTimeout, TimeUnit.SECONDS)
              .getMessageStream(messageStreamRequest);
      while (messageStreamIterator.hasNext()) {
        JobMessage messageResponse = messageStreamIterator.next().getMessageResponse();
        if (messageResponse.getImportance() == JobMessage.MessageImportance.JOB_MESSAGE_ERROR) {
          throw new RuntimeException(
              "The Runner experienced the following error during execution:\n"
                  + messageResponse.getMessageText());
        }
      }
    }
  }

  private static State getJavaState(JobApi.JobState.Enum protoState) {
    switch (protoState) {
      case UNSPECIFIED:
        return State.UNKNOWN;
      case STOPPED:
        return State.STOPPED;
      case RUNNING:
        return State.RUNNING;
      case DONE:
        return State.DONE;
      case FAILED:
        return State.FAILED;
      case CANCELLED:
        return State.CANCELLED;
      case UPDATED:
        return State.UPDATED;
      case DRAINING:
        // TODO: Determine the correct mappings for the states below.
        return State.UNKNOWN;
      case DRAINED:
        return State.UNKNOWN;
      case STARTING:
        return State.RUNNING;
      case CANCELLING:
        return State.CANCELLED;
      default:
        LOG.warn("Unrecognized state from server: {}", protoState);
        return State.UNKNOWN;
    }
  }
}


text:
'use strict'

async function _voneFetch (auth = {}, method = 'GET', request = 'rest-1.v1/Data/Scope/0', input) {
  // auth = {getFetch, vone, credentials, agent}
  if (auth.getFetch === undefined) { throw new Error('voneFetch: getFetch() is undefined') }
  if (auth.vone === undefined) { throw new Error('voneFetch: VersionOne URL is undefined') }

  // fetch parameters
  const fetch = auth.getFetch()
  const url = auth.vone + '/' + request
  const body = input && JSON.stringify(input)
  const headers = auth.credentials
    ? { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': auth.credentials }
    : { 'Accept': 'application/json', 'Content-Type': 'application/json' }
  const [mode, credentials, agent] = ['cors', 'include', auth.agent]
  // console.log(url, method, body, headers, mode, credentials, agent)

  // fetch promise
  console.log('BEGINNING OF REST CALL')
  return new Promise((resolve, reject) => {
    fetch(url, {method, body, headers, mode, credentials, agent})
    .then(resp => {
      const { ok, status, statusText } = resp
      const response = { ok, status, statusText }
      if (!resp.ok) {
        // The error could be embedded in a json response
        resp.json()
        .catch(() => reject(new Error(JSON.stringify(response)))) // The error is not embedded in a json response
        .then(json => { // Keep only the non-empty attributes from the json response
          const err = {}
          for (let attr in json) {
            if (Object.keys(json[attr]).length > 0) { // json[attr] is either array or object
              err[attr] = json[attr]
            }
          }
          reject(new Error(JSON.stringify(err)))
        })
      } else {
        const whoami = resp.headers.get('V1-MemberID')
        if (resp.status === 204) { // means statusText === 'No Content'
          resolve({whoami, data: response})
        } else {
          // resp.json().then(json => { resolve(json) })
          // resp.text().then(text => { resolve(text) })
          resp.json()
          .catch(() => {
            if (resp._raw.length > 0) {
              const data = resp._raw.toString()
              resolve({whoami, data})
            } else {
              resolve({whoami, data: response})
            }
          }).then(data => resolve({whoami, data}))
        }
      }
    })
    .catch(err => reject(err))
    .then(() => {
      console.log('END OF REST CALL')
    })
  })
}

async function getWhoAmI (auth, method, request, input) {
  return _voneFetch(auth, method, request, input).then(res => res.whoami)
}

async function voneFetch (auth, method, request, input) {
  return _voneFetch(auth, method, request, input).then(res => res.data)
}

module.exports = { voneFetch, getWhoAmI }


text:
package org.pepstock.charba.client.defaults;

import java.util.List;

import org.pepstock.charba.client.commons.Key;
import org.pepstock.charba.client.defaults.globals.DefaultNumberFormatOptions;
import org.pepstock.charba.client.intl.NumberFormatOptions;
import org.pepstock.charba.client.intl.enums.CompactDisplay;
import org.pepstock.charba.client.intl.enums.Currency;
import org.pepstock.charba.client.intl.enums.CurrencyDisplay;
import org.pepstock.charba.client.intl.enums.CurrencySign;
import org.pepstock.charba.client.intl.enums.MeasureUnit;
import org.pepstock.charba.client.intl.enums.MeasureUnitDisplay;
import org.pepstock.charba.client.intl.enums.Notation;
import org.pepstock.charba.client.intl.enums.SignDisplay;
import org.pepstock.charba.client.intl.enums.Style;
import org.pepstock.charba.client.items.NumberFormatItem;

/**
 * Interface to define the number format options for internationalization.
 *
 * @author Andrea "Stock" Stocchero
 */
public interface IsDefaultNumberFormatOptions extends IsDefaultBaseFormatOptions {

	/**
	 * Returns the compact display when {@link Notation#COMPACT} is set.
	 *
	 * @return the compact display when {@link Notation#COMPACT} is set
	 */
	CompactDisplay getCompactDisplay();

	/**
	 * Returns the currency to use in currency formatting.
	 *
	 * @return the currency to use in currency formatting
	 */
	Currency getCurrency();

	/**
	 * Returns how to display the currency in currency formatting.
	 *
	 * @return how to display the currency in currency formatting
	 */
	CurrencyDisplay getCurrencyDisplay();

	/**
	 * In many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign.

	 * You can enable this formatting by setting the currency sign option to "accounting" otherwise "standard".
	 *
	 * @return the currency format to use on formatting
	 */
	CurrencySign getCurrencySign();

	/**
	 * Returns the formatting that should be displayed for the number.
	 *
	 * @return the formatting that should be displayed for the number
	 */
	Notation getNotation();

	/**
	 * Returns when to display the sign for the number.
	 *
	 * @return when to display the sign for the number
	 */
	SignDisplay getSignDisplay();

	/**
	 * Returns the formatting style to use.
	 *
	 * @return the formatting style to use
	 */
	Style getStyle();

	/**
	 * Returns an unmodifiable list of units to use in unit formatting.
	 *
	 * @return an unmodifiable list of unit to use in unit formatting
	 */
	List<MeasureUnit> getUnitsOfMeasure();

	/**
	 * Returns the unit formatting style to use in unit formatting.
	 *
	 * @return the unit formatting style to use in unit formatting
	 */
	MeasureUnitDisplay getUnitOfMeasureDisplay();

	/**
	 * Returns true whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators.
	 *
	 * @return true whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators
	 */
	boolean isUseGrouping();

	/**
	 * Returns the minimum number of integer digits to use.
	 *
	 * @return the minimum number of integer digits to use
	 */
	int getMinimumIntegerDigits();

	/**
	 * Returns the minimum number of fraction digits to use.

	 * The default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the currency, see
	 * {@link Currency#getMinimumFractionDigits()}.
	 *
	 * @return the minimum number of fraction digits to use.

	 *         The default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the currency, see
	 *         {@link Currency#getMinimumFractionDigits()}
	 */
	default int getMinimumFractionDigits() {
		// the default for plain number and percent formatting is 0
		// the default for currency formatting is the number of minor unit digits provided by the currency.
		// gets style to get the default
		Style style = getStyle();
		// creates the default reference
		int defaultDigits = 0;
		// checks if there is the currency style is activate
		if (Style.CURRENCY.equals(style)) {
			// get currency
			Currency currency = getCurrency();
			// checks if currency is consistent
			if (Key.isValid(currency)) {
				// sets default
				defaultDigits = currency.getMinimumFractionDigits();
			}
		}
		return defaultDigits;
	}

	/**
	 * Returns the maximum number of fraction digits to use.

	 * The default for plain number formatting is the larger of {@link NumberFormatOptions#getMinimumFractionDigits()} and 3.

	 * The default for currency formatting is the larger of {@link NumberFormatOptions#getMinimumFractionDigits()} and the number of minor unit digits provided by currency, see
	 * {@link Currency#getMinimumFractionDigits()}.

	 * The default for percent formatting is the larger of {@link NumberFormatOptions#getMinimumFractionDigits()} and 0.
	 *
	 * @return the maximum number of fraction digits to use.

	 *         The default for plain number formatting is the larger of {@link NumberFormatOptions#getMinimumFractionDigits()} and 3.

	 *         The default for currency formatting is the larger of {@link NumberFormatOptions#getMinimumFractionDigits()} and the number of minor unit digits provided by currency,
	 *         see {@link Currency#getMinimumFractionDigits()}.

	 *         The default for percent formatting is the larger of {@link NumberFormatOptions#getMinimumFractionDigits()} and 0.
	 */
	default int getMaximumFractionDigits() {
		// the default for plain number formatting is the larger of minimumFractionDigits and 3
		// the default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by currency
		// the default for percent formatting is the larger of minimumFractionDigits and 0.
		// gets style to get the default
		Style style = getStyle();
		// creates the default reference
		// the default for plain number formatting is the larger of minimumFractionDigits and 3
		int defaultDigits = Math.max(getMinimumFractionDigits(), 3);
		// checks if there is the currency style is activate
		if (Style.CURRENCY.equals(style)) {
			// get currency
			Currency currency = getCurrency();
			// checks if currency is consistent
			if (Key.isValid(currency)) {
				// the default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by currency
				defaultDigits = Math.max(getMinimumFractionDigits(), currency.getMinimumFractionDigits());
			}
		} else if (Style.PERCENT.equals(style)) {
			// the default for percent formatting is the larger of minimumFractionDigits and 0.
			defaultDigits = Math.max(getMinimumFractionDigits(), 0);
		}
		return defaultDigits;
	}

	/**
	 * Returns the minimum number of significant digits to use.
	 *
	 * @return the minimum number of significant digits to use
	 */
	int getMinimumSignificantDigits();

	/**
	 * Returns the maximum number of significant digits to use.
	 *
	 * @return the maximum number of significant digits to use
	 */
	int getMaximumSignificantDigits();

	/**
	 * Creates a number format options instance using default or cloning current instance.
	 *
	 * @return a number format options instance using default or cloning current instance
	 */
	default NumberFormatItem create() {
		return create(new DefaultNumberFormatOptions());
	}

	/**
	 * Creates a number format options instance using default or cloning current instance.
	 *
	 * @param defaultValues default provider
	 * @return a number format options instance using default or cloning current instance
	 */
	default NumberFormatItem create(IsDefaultNumberFormatOptions defaultValues) {
		// creates new number format item
		NumberFormatItem result = new NumberFormatItem(defaultValues);
		// loads number format
		result.setLocaleMatcher(getLocaleMatcher());
		result.setNumberingSystem(getNumberingSystem());
		result.setCompactDisplay(getCompactDisplay());
		result.setCurrency(getCurrency());
		result.setCurrencyDisplay(getCurrencyDisplay());
		result.setCurrencySign(getCurrencySign());
		result.setNotation(getNotation());
		result.setSignDisplay(getSignDisplay());
		result.setStyle(getStyle());
		result.setUnitsOfMeasure(getUnitsOfMeasure());
		result.setUnitOfMeasureDisplay(getUnitOfMeasureDisplay());
		result.setUseGrouping(isUseGrouping());
		result.setMinimumIntegerDigits(getMinimumIntegerDigits());
		result.setMinimumFractionDigits(getMinimumFractionDigits());
		result.setMaximumFractionDigits(getMaximumFractionDigits());
		result.setMinimumSignificantDigits(getMinimumIntegerDigits());
		result.setMaximumSignificantDigits(getMinimumIntegerDigits());
		// returns number format item
		return result;
	}

}


text:
NAME=windowsxp-sp3-xp_mode

# design time
VBoxManage modifyvm ${NAME} --clipboard bidirectional

# runtime
VBoxManage controlvm ${NAME} clipboard bidirectional


text:
<?php

declare(strict_types=1);

namespace FondBot\Foundation;

use FondBot\Channels\Channel;

class Kernel
{
    public const VERSION = '3.0.23';

    /** @var Channel|null */
    private $channel;

    /**
     * Initialize kernel.
     *
     * @param Channel $channel
     */
    public function initialize(Channel $channel): void
    {
        $this->channel = $channel;
    }

    /**
     * Get current channel.
     *
     * @return Channel|null
     */
    public function getChannel(): ?Channel
    {
        return $this->channel;
    }
}


text:
package jodd.petite.data;

public class MyBiz3  implements Biz {

	@Override
	public void calculate() {
	}
}


text:
package net.fortytwo.smsn.speech;

import edu.cmu.sphinx.frontend.util.Microphone;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Joshua Shinavier (http://fortytwo.net)
 */
public class SpeechAgent {
    private static final Speaker SPEAKER = new Speaker();

    private final BlockingQueue<Result> queue = new LinkedBlockingQueue<Result>();
    private boolean listening;

    private synchronized void startListening() {
        System.out.println("LISTENING ----------------");
        listening = true;
    }

    private synchronized void stopListening() {
        System.out.println("--------------------------");
        listening = false;
    }

    private synchronized boolean isListening() {
        return listening;
    }

    public static void main(String[] args) {
        try {
            new SpeechAgent().doit();
        } catch (Throwable t) {
            t.printStackTrace(System.err);
            System.exit(1);
        }
    }

    private void doit() throws InterruptedException {
        ConfigurationManager cm = new ConfigurationManager(SpeechAgent.class.getResource("smsn-speech.config.xml"));

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    Result r = null;
                    try {
                        r = queue.take();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    stopListening();
                    float score = -1 * r.getBestFinalToken().getScore() / 1000f;

                    System.out.println("got result: " + r + " (" + score + ")");
                    if (score < 5000) {
                        System.out.println("\tscore is too low");
                    } else {
                        String text = r.getBestFinalResultNoFiller().trim().toLowerCase();

                        if (text.startsWith("computer")) {
                            if (text.equals("computer time")) {
                                SPEAKER.speak("it is " + spokenTime());
                            } else if (text.equals("computer date")) {
                                SPEAKER.speak("it is " + spokenDate());
                            } else {
                                SPEAKER.speak("you said: " + text);
                            }

                            // Grace period keeps the recognizer from reacting to the speaker's voice.
                            // It takes some time to pull the last result out of the recognizer and throw it away.
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw new IllegalStateException(e);
                            }
                        } else {
                            System.out.println("\tred herring");
                        }
                    }

                    startListening();
                }
            }
        }.start();

        Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
        //recognizer.addResultListener(listener);
        recognizer.allocate();

        // start the microphone or exit if the program if this is not possible
        Microphone microphone = (Microphone) cm.lookup("microphone");
        if (!microphone.startRecording()) {
            System.out.println("Cannot start microphone.");
            recognizer.deallocate();
            System.exit(1);
        }

        startListening();
        System.out.println("Start speaking.\n");
        while (true) {
            System.out.println("recognizing...");
            Result result = recognizer.recognize();
            System.out.println("\tdone.");

            if (result != null) {
                System.out.println("pulled result: " + result);
                if (isListening() && result.getBestFinalResultNoFiller().length() > 0) {
                    System.out.println("\tadding to queue");
                    queue.put(result);
                }
            } else {
                System.out.println("I can't hear what you said.\n");
            }
        }
    }

    private static final String[] MONTH_NAMES = {
            "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "October", "November", "December"};

    private String spokenDate() {
        Calendar c = new GregorianCalendar();
        c.setTime(new Date());

        StringBuilder sb = new StringBuilder();

        sb.append(MONTH_NAMES[c.get(Calendar.MONTH)]);
        sb.append(" ");
        sb.append(c.get(Calendar.DAY_OF_MONTH));
        sb.append(", ");
        sb.append(c.get(Calendar.YEAR));

        return sb.toString();
    }

    private String spokenTime() {
        Calendar c = new GregorianCalendar();
        c.setTime(new Date());

        StringBuilder sb = new StringBuilder();

        sb.append(c.get(Calendar.HOUR));
        sb.append(" ");

        int min = c.get(Calendar.MINUTE);
        if (0 == min) {
            sb.append("o' clock");
        } else if (min < 10) {
            sb.append("oh ").append(min);
        } else {
            sb.append(min);
        }

        sb.append(" ");
        sb.append(c.get(Calendar.HOUR_OF_DAY) >= 12 ? "PM" : "AM");

        return sb.toString();
    }
}


text:
<!DOCTYPE html>

		<meta charset=UTF-8>
		<title>vanham.io</title>
		<meta name=viewport content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
		<link rel=icon type=image/x-icon href=/static/img/favicon.ico>
		<link rel="manifest" href="/manifest.json">
		<meta name="theme-color" content="#181849">

		{{{css}}}

			<svg><use xlink:href="/static/img/sprite.svg#cover-icon"/></svg>

				Daan van Ham
				Developer

				back

					{title}

{intro}

					{created}

			{title}

{intro}

			<svg><use xlink:href="/static/img/sprite.svg#octocat-icon"/></svg>
			<svg><use xlink:href="/static/img/sprite.svg#twitter-icon"/></svg>
			<svg><use xlink:href="/static/img/sprite.svg#instagram-icon"/></svg>

		{{{js}}}


text:
class MailPluginManager < Cask
  version :latest
  sha256 :no_check

  url 'http://www.chungwasoft.com/files/MPM_latest.zip'
  homepage 'http://www.chungwasoft.com/mailpluginmanager/'
  license :unknown

  app 'Mail Plugin Manager.app'
end


text:
package kubernetes

import (
	"context"
	"crypto/md5"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"reflect"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-containerregistry/pkg/authn"
	"github.com/google/go-containerregistry/pkg/name"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	fakeclient "k8s.io/client-go/kubernetes/fake"
)

var dockerSecretTypes = []secretType{
	dockerConfigJSONSecretType,
	dockerCfgSecretType,
}

type secretType struct {
	name    corev1.SecretType
	key     string
	marshal func(t *testing.T, registry string, auth authn.AuthConfig) []byte
}

func (s *secretType) Create(t *testing.T, namespace, name string, registry string, auth authn.AuthConfig) *corev1.Secret {
	return &corev1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: namespace,
		},
		Type: s.name,
		Data: map[string][]byte{
			s.key: s.marshal(t, registry, auth),
		},
	}
}

var dockerConfigJSONSecretType = secretType{
	name: corev1.SecretTypeDockerConfigJson,
	key:  corev1.DockerConfigJsonKey,
	marshal: func(t *testing.T, target string, auth authn.AuthConfig) []byte {
		return toJSON(t, dockerConfigJSON{
			Auths: map[string]authn.AuthConfig{target: auth},
		})
	},
}

var dockerCfgSecretType = secretType{
	name: corev1.SecretTypeDockercfg,
	key:  corev1.DockerConfigKey,
	marshal: func(t *testing.T, target string, auth authn.AuthConfig) []byte {
		return toJSON(t, map[string]authn.AuthConfig{target: auth})
	},
}

func TestAnonymousFallback(t *testing.T) {
	client := fakeclient.NewSimpleClientset(&corev1.ServiceAccount{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "default",
			Namespace: "default",
		},
	})

	kc, err := New(context.Background(), client, Options{})
	if err != nil {
		t.Errorf("New() = %v", err)
	}

	testResolve(t, kc, registry(t, "fake.registry.io"), authn.Anonymous)
}

func TestAnonymousFallbackNoServiceAccount(t *testing.T) {
	kc, err := New(context.Background(), nil, Options{
		ServiceAccountName: NoServiceAccount,
	})
	if err != nil {
		t.Errorf("New() = %v", err)
	}

	testResolve(t, kc, registry(t, "fake.registry.io"), authn.Anonymous)
}

func TestSecretNotFound(t *testing.T) {
	client := fakeclient.NewSimpleClientset()

	kc, err := New(context.Background(), client, Options{
		ServiceAccountName: NoServiceAccount,
		ImagePullSecrets:   []string{"not-found"},
	})
	if err != nil {
		t.Errorf("New() = %v", err)
	}

	testResolve(t, kc, registry(t, "fake.registry.io"), authn.Anonymous)
}

func TestServiceAccountNotFound(t *testing.T) {
	client := fakeclient.NewSimpleClientset(&corev1.ServiceAccount{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "default",
			Namespace: "default",
		},
	})
	kc, err := New(context.Background(), client, Options{
		ServiceAccountName: "not-found",
	})
	if err != nil {
		t.Errorf("New() = %v", err)
	}

	testResolve(t, kc, registry(t, "fake.registry.io"), authn.Anonymous)
}

func TestAttachedServiceAccount(t *testing.T) {
	username, password := "foo", "bar"
	client := fakeclient.NewSimpleClientset(&corev1.ServiceAccount{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "svcacct",
			Namespace: "ns",
		},
		ImagePullSecrets: []corev1.LocalObjectReference{{
			Name: "secret",
		}},
	},
		dockerCfgSecretType.Create(t, "ns", "secret", "fake.registry.io", authn.AuthConfig{
			Username: username,
			Password: password,
		}),
	)

	kc, err := New(context.Background(), client, Options{
		Namespace:          "ns",
		ServiceAccountName: "svcacct",
	})
	if err != nil {
		t.Fatalf("New() = %v", err)
	}

	testResolve(t, kc, registry(t, "fake.registry.io"),
		&authn.Basic{Username: username, Password: password})
}

// Prioritze picking the first secret
func TestSecretPriority(t *testing.T) {
	secrets := []corev1.Secret{
		*dockerCfgSecretType.Create(t, "ns", "secret", "fake.registry.io", authn.AuthConfig{
			Username: "user", Password: "pass",
		}),
		*dockerCfgSecretType.Create(t, "ns", "secret-2", "fake.registry.io", authn.AuthConfig{
			Username: "anotherUser", Password: "anotherPass",
		}),
	}

	kc, err := NewFromPullSecrets(context.Background(), secrets)
	if err != nil {
		t.Fatalf("NewFromPullSecrets() = %v", err)
	}

	expectedAuth := &authn.Basic{Username: "user", Password: "pass"}
	testResolve(t, kc, registry(t, "fake.registry.io"), expectedAuth)
}

func TestResolveTargets(t *testing.T) {
	// Iterate over target types
	targetTypes := []authn.Resource{
		registry(t, "fake.registry.io"),
		repo(t, "fake.registry.io/repo"),
	}

	for _, secretType := range dockerSecretTypes {
		for _, target := range targetTypes {
			// Drop the .
			testName := secretType.key[1:] + "_" + target.String()

			t.Run(testName, func(t *testing.T) {
				auth := authn.AuthConfig{
					Password: fmt.Sprintf("%x", md5.Sum([]byte(t.Name()))),
					Username: "user" + fmt.Sprintf("%x", md5.Sum([]byte(t.Name()))),
				}

				kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{
					*secretType.Create(t, "ns", "secret", target.String(), auth),
				})

				if err != nil {
					t.Fatalf("New() = %v", err)
				}
				authenticator := &authn.Basic{Username: auth.Username, Password: auth.Password}
				testResolve(t, kc, target, authenticator)
			})
		}
	}
}

func TestAuthWithScheme(t *testing.T) {
	auth := authn.AuthConfig{
		Password: "password",
		Username: "username",
	}

	kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{
		*dockerConfigJSONSecretType.Create(t, "ns", "secret", "https://fake.registry.io", auth),
	})

	if err != nil {
		t.Fatalf("New() = %v", err)
	}
	authenticator := &authn.Basic{Username: auth.Username, Password: auth.Password}
	testResolve(t, kc, registry(t, "fake.registry.io"), authenticator)
	testResolve(t, kc, repo(t, "fake.registry.io/repo"), authenticator)
}

func TestAuthWithPorts(t *testing.T) {
	auth := authn.AuthConfig{
		Password: "password",
		Username: "username",
	}

	kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{
		*dockerConfigJSONSecretType.Create(t, "ns", "secret", "fake.registry.io:5000", auth),
	})

	if err != nil {
		t.Fatalf("New() = %v", err)
	}
	authenticator := &authn.Basic{Username: auth.Username, Password: auth.Password}
	testResolve(t, kc, registry(t, "fake.registry.io:5000"), authenticator)
	testResolve(t, kc, repo(t, "fake.registry.io:5000/repo"), authenticator)

	// Non-matching ports should return Anonymous
	testResolve(t, kc, registry(t, "fake.registry.io:1000"), authn.Anonymous)
	testResolve(t, kc, repo(t, "fake.registry.io:1000/repo"), authn.Anonymous)
}

func TestAuthPathMatching(t *testing.T) {
	rootAuth := authn.AuthConfig{Username: "root", Password: "root"}
	nestedAuth := authn.AuthConfig{Username: "nested", Password: "nested"}
	leafAuth := authn.AuthConfig{Username: "leaf", Password: "leaf"}
	partialAuth := authn.AuthConfig{Username: "partial", Password: "partial"}

	kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{
		*dockerConfigJSONSecretType.Create(t, "ns", "secret-1", "fake.registry.io", rootAuth),
		*dockerConfigJSONSecretType.Create(t, "ns", "secret-2", "fake.registry.io/nested", nestedAuth),
		*dockerConfigJSONSecretType.Create(t, "ns", "secret-3", "fake.registry.io/nested/repo", leafAuth),
		*dockerConfigJSONSecretType.Create(t, "ns", "secret-4", "fake.registry.io/par", partialAuth),
	})

	if err != nil {
		t.Fatalf("New() = %v", err)
	}
	testResolve(t, kc, registry(t, "fake.registry.io"), authn.FromConfig(rootAuth))
	testResolve(t, kc, repo(t, "fake.registry.io/nested"), authn.FromConfig(nestedAuth))
	testResolve(t, kc, repo(t, "fake.registry.io/nested/repo"), authn.FromConfig(leafAuth))
	testResolve(t, kc, repo(t, "fake.registry.io/nested/repo/dirt"), authn.FromConfig(leafAuth))
	testResolve(t, kc, repo(t, "fake.registry.io/partial"), authn.FromConfig(partialAuth))
}

func TestAuthHostNameVariations(t *testing.T) {
	rootAuth := authn.AuthConfig{Username: "root", Password: "root"}
	subdomainAuth := authn.AuthConfig{Username: "sub", Password: "sub"}

	kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{
		*dockerConfigJSONSecretType.Create(t, "ns", "secret-1", "fake.registry.io", rootAuth),
		*dockerConfigJSONSecretType.Create(t, "ns", "secret-2", "1.fake.registry.io", subdomainAuth),
	})

	if err != nil {
		t.Fatalf("New() = %v", err)
	}

	testResolve(t, kc, registry(t, "fake.registry.io"), authn.FromConfig(rootAuth))
	testResolve(t, kc, registry(t, "1.fake.registry.io"), authn.FromConfig(subdomainAuth))

	// Unrecognized subdomain uses Anonymous
	testResolve(t, kc, registry(t, "2.fake.registry.io"), authn.Anonymous)
}

func TestAuthSpecialPathsIgnored(t *testing.T) {
	auth := authn.AuthConfig{Username: "root", Password: "root"}
	auth2 := authn.AuthConfig{Username: "root2", Password: "root2"}

	kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{
		// Note the paths need a trailing '/'
		*dockerConfigJSONSecretType.Create(t, "ns", "secret-1", "https://fake.registry.io/v1/", auth),
		*dockerConfigJSONSecretType.Create(t, "ns", "secret-2", "https://fake2.registry.io/v2/", auth2),
	})

	if err != nil {
		t.Fatalf("New() = %v", err)
	}

	testResolve(t, kc, registry(t, "fake.registry.io"), authn.FromConfig(auth))
	testResolve(t, kc, repo(t, "fake.registry.io/repo"), authn.FromConfig(auth))
	testResolve(t, kc, registry(t, "fake2.registry.io"), authn.FromConfig(auth2))
	testResolve(t, kc, repo(t, "fake2.registry.io/repo"), authn.FromConfig(auth2))
}

func TestAuthDockerRegistry(t *testing.T) {
	auth := authn.AuthConfig{Username: "root", Password: "root"}
	kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{
		*dockerConfigJSONSecretType.Create(t, "ns", "secret", "index.docker.io", auth),
	})

	if err != nil {
		t.Fatalf("New() = %v", err)
	}

	testResolve(t, kc, repo(t, "ubuntu"), authn.FromConfig(auth))
	testResolve(t, kc, repo(t, "knative/serving"), authn.FromConfig(auth))
}

func TestAuthWithGlobs(t *testing.T) {
	auth := authn.AuthConfig{Username: "root", Password: "root"}
	kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{
		*dockerConfigJSONSecretType.Create(t, "ns", "secret", "*.registry.io", auth),
	})

	if err != nil {
		t.Fatalf("New() = %v", err)
	}

	testResolve(t, kc, registry(t, "fake.registry.io"), authn.FromConfig(auth))
	testResolve(t, kc, repo(t, "fake.registry.io/repo"), authn.FromConfig(auth))
	testResolve(t, kc, registry(t, "blah.registry.io"), authn.FromConfig(auth))
	testResolve(t, kc, repo(t, "blah.registry.io/repo"), authn.FromConfig(auth))
}

func testResolve(t *testing.T, kc authn.Keychain, target authn.Resource, expectedAuth authn.Authenticator) {
	t.Helper()

	auth, err := kc.Resolve(target)
	if err != nil {
		t.Errorf("Resolve(%v) = %v", target, err)
	}
	got, err := auth.Authorization()
	if err != nil {
		t.Errorf("Authorization() = %v", err)
	}
	want, err := expectedAuth.Authorization()
	if err != nil {
		t.Errorf("Authorization() = %v", err)
	}
	if diff := cmp.Diff(want, got); diff != "" {
		t.Error("Resolve() diff (-want, +got)\n", diff)
	}
}

func toJSON(t *testing.T, obj interface{}) []byte {
	t.Helper()

	bites, err := json.Marshal(obj)

	if err != nil {
		t.Fatal("unable to json marshal", err)
	}
	return bites
}

func registry(t *testing.T, registry string) authn.Resource {
	t.Helper()

	reg, err := name.NewRegistry(registry, name.WeakValidation)
	if err != nil {
		t.Fatal("failed to create registry", err)
	}
	return reg
}

func repo(t *testing.T, repository string) authn.Resource {
	t.Helper()

	repo, err := name.NewRepository(repository, name.WeakValidation)
	if err != nil {
		t.Fatal("failed to create repo", err)
	}
	return repo
}

// TestDockerConfigJSON tests using secrets using the .dockerconfigjson form,
// like you might get from running:
// kubectl create secret docker-registry secret -n ns --docker-server="fake.registry.io" --docker-username="foo" --docker-password="bar"
func TestDockerConfigJSON(t *testing.T) {
	username, password := "foo", "bar"
	kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "secret",
			Namespace: "ns",
		},
		Type: corev1.SecretTypeDockerConfigJson,
		Data: map[string][]byte{
			corev1.DockerConfigJsonKey: []byte(
				fmt.Sprintf(`{"auths":{"fake.registry.io":{"username":%q,"password":%q,"auth":%q}}}`,
					username, password,
					base64.StdEncoding.EncodeToString([]byte(username+":"+password))),
			),
		},
	}})
	if err != nil {
		t.Fatalf("NewFromPullSecrets() = %v", err)
	}

	reg, err := name.NewRegistry("fake.registry.io", name.WeakValidation)
	if err != nil {
		t.Errorf("NewRegistry() = %v", err)
	}

	auth, err := kc.Resolve(reg)
	if err != nil {
		t.Errorf("Resolve(%v) = %v", reg, err)
	}
	got, err := auth.Authorization()
	if err != nil {
		t.Errorf("Authorization() = %v", err)
	}
	want, err := (&authn.Basic{Username: username, Password: password}).Authorization()
	if err != nil {
		t.Errorf("Authorization() = %v", err)
	}
	if !reflect.DeepEqual(got, want) {
		t.Errorf("Resolve() = %v, want %v", got, want)
	}
}

func TestKubernetesAuth(t *testing.T) {
	// From https://github.com/knative/serving/issues/12761#issuecomment-1097441770
	// All of these should work with K8s' docker auth parsing.
	for k, ss := range map[string][]string{
		"registry.gitlab.com/dprotaso/test/nginx": []string{
			"registry.gitlab.com",
			"http://registry.gitlab.com",
			"https://registry.gitlab.com",
			"registry.gitlab.com/dprotaso",
			"http://registry.gitlab.com/dprotaso",
			"https://registry.gitlab.com/dprotaso",
			"registry.gitlab.com/dprotaso/test",
			"http://registry.gitlab.com/dprotaso/test",
			"https://registry.gitlab.com/dprotaso/test",
			"registry.gitlab.com/dprotaso/test/nginx",
			"http://registry.gitlab.com/dprotaso/test/nginx",
			"https://registry.gitlab.com/dprotaso/test/nginx",
		},
		"dtestcontainer.azurecr.io/dave/nginx": []string{
			"dtestcontainer.azurecr.io",
			"http://dtestcontainer.azurecr.io",
			"https://dtestcontainer.azurecr.io",
			"dtestcontainer.azurecr.io/dave",
			"http://dtestcontainer.azurecr.io/dave",
			"https://dtestcontainer.azurecr.io/dave",
			"dtestcontainer.azurecr.io/dave/nginx",
			"http://dtestcontainer.azurecr.io/dave/nginx",
			"https://dtestcontainer.azurecr.io/dave/nginx",
		}} {
		repo, err := name.NewRepository(k)
		if err != nil {
			t.Errorf("parsing %q: %v", k, err)
			continue
		}

		for _, s := range ss {
			t.Run(fmt.Sprintf("%s - %s", k, s), func(t *testing.T) {
				username, password := "foo", "bar"
				kc, err := NewFromPullSecrets(context.Background(), []corev1.Secret{{
					ObjectMeta: metav1.ObjectMeta{
						Name:      "secret",
						Namespace: "ns",
					},
					Type: corev1.SecretTypeDockerConfigJson,
					Data: map[string][]byte{
						corev1.DockerConfigJsonKey: []byte(
							fmt.Sprintf(`{"auths":{%q:{"username":%q,"password":%q,"auth":%q}}}`,
								s,
								username, password,
								base64.StdEncoding.EncodeToString([]byte(username+":"+password))),
						),
					},
				}})
				if err != nil {
					t.Fatalf("NewFromPullSecrets() = %v", err)
				}
				auth, err := kc.Resolve(repo)
				if err != nil {
					t.Errorf("Resolve(%v) = %v", repo, err)
				}
				got, err := auth.Authorization()
				if err != nil {
					t.Errorf("Authorization() = %v", err)
				}
				want, err := (&authn.Basic{Username: username, Password: password}).Authorization()
				if err != nil {
					t.Errorf("Authorization() = %v", err)
				}
				if !reflect.DeepEqual(got, want) {
					t.Errorf("Resolve() = %v, want %v", got, want)
				}
			})
		}
	}
}


text:
require 'restforce'

module RdApi

  class Contact
    attr_accessor :client

    def initialize(attrs)
      @client = Restforce.new(attrs)
    end

    def all
      @client.query('select Id, Account.Name, Account.Site, Phone, Email from Contact')
    end

    def find_by_id(id)
      @client.find('Contact', id)
    end

    def create(name, phone, email)
      @client.create('Contact', LastName: name)
    end

    def update(id, name, phone, email)
      @client.update('Contact', Id: id, LastName: name)
    end

    def destroy(id)
      @client.destroy('Contact', id)
    end
  end
end


text:
title: "Loading Cell Renderer"
---

Loading cell renderers allow you to add your own loading renderers to ag-Grid. Use these when the provided loading renderers do not meet your requirements.

## Loading Cell Renderer Interface

Implement this interface to provide a custom loading cell renderer when loading rows.

```ts
interface ILoadingCellRenderer {
    // mandatory methods

    // The init(params) method is called on the loading cell renderer once. See below for details on the parameters.
    init(params: ILoadingCellRendererParams): void;

    // Returns the DOM element for this loading cell renderer
    getGui(): HTMLElement;
}
```

```ts
interface ILoadingCellRendererParams {
    // an optional template for the loading cell renderer
    loadingMessage?: string

    // The grid API
    api: any;
}
```

## Registering Loading Cell Renderer Components

See the section [registering custom components](../components/#registering-custom-components) for details on registering and using custom loading cell renderers.

## Example: Custom Loading Cell Renderer

The example below demonstrates how to provide custom loading cell renderer component to the grid. Notice the following:

- **Custom Loading Cell Renderer** is supplied by name via `gridOptions.loadingCellRenderer`.
- **Custom Loading Cell Renderer Parameters** are supplied using `gridOptions.loadingCellRendererParams`.

<grid-example title='Custom Loading Cell Renderer' name='custom-loading-cell-renderer' type='generated' options='{ "enterprise": true, "extras": ["fontawesome"] }'></grid-example>


text:
package io.reflectoring.coderadar.rest.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class GetUserResponse {
  private long id;
  private String username;
  private boolean platformAdmin = false;
}


text:
'use strict';

suite('StaticView', function(){
	suite('Constructor', function(){
		teardown(function(){
			StaticView.instance = null;
		});

		test('initialize', function(){
			new StaticView();
		});

		test('is singleton', function(){
			assert.equal(new StaticView(), new StaticView(), 'StaticView should behave as singleton');
		});
	});

	suite('Methods', function(){
		var view;
		setup(function() {
			view = new StaticView();
		});
		teardown(function(){
			view = null;
			StaticView.instance = null;
		});

		suite('render', function(){
			setup(function(){
				sinon.stub(view, "_initElements");
				sinon.stub(view, "_attachEvents");
			});
			teardown(function(){
				view._initElements.restore();
				view._attachEvents.restore();
			});

			test('order of helper methods', function(){
				view.render();

				assert.isTrue(view._initElements.calledOnce, '_initElements should be called once');
				assert.isTrue(view._attachEvents.calledOnce, '_initElements should be called once');
				assert.isTrue(view._attachEvents.calledAfter(view._initElements), 'Helper methods were called in incorrect order by rendering');
			});
		});

		['show', 'hide'].forEach(function(method) {
			test(method + '()', function() {
				view.element = document.createElement('div');

				view[method]();
			});
		});
	});

	suite('Destruction', function(){
		setup(function(){
			sinon.spy(AView.prototype, 'destruct');
			sinon.spy(Element.prototype, 'remove');
		});
		teardown(function(){
			StaticView.instance = null;

			AView.prototype.destruct.restore();
			Element.prototype.remove.restore();
		});

		test('the element should be removed and then parent\s method should be called', function(){
			var view = new StaticView();
			view.element = document.createElement('div');
			view.render();
			view.destruct();

			assert.isTrue(Element.prototype.remove.calledOnce);
			assert.isTrue(AView.prototype.destruct.calledOnce);
			assert.isTrue(AView.prototype.destruct.calledAfter(Element.prototype.remove));
		});
	});
});


text:
USER_SCRIPT="user-script.sh"
[[ -f $USER_SCRIPT ]] && echo "Running ${USER_SCRIPT}" && bash ${USER_SCRIPT} || echo "${USER_SCRIPT} not found/executed, continuing."
#apt-get update
#apt-get --yes remove openjdk-6-jre-headless
#apt-get --yes install openjdk-7-jdk


text:
<?php
if ( ! defined('BASEPATH')) exit('Sem acesso direto ao script');

class MY_Home extends CI_Controller{
  public $this->data;
  public function __CONSTRUCT(){
    parent::__CONSTRUCT();
    $this->_quantidade_carrinho();
  }
  private function _quantidade_carrinho()
  {
    $quantidade_carrinho = count($this->session->carrinho);
    $this->data['quantidade_carrinho'] = $quantidade_carrinho;
    return $quantidade_carrinho;
  }

}


text:
/*jslint browser: true*/
/*global angular*/
/*global $*/
/*global console*/
var haPi = angular.module("haPi", ['ui.router', 'ui.bootstrap', 'chart.js', 'ngPrettyJson']);

haPi.config(function ($stateProvider, $urlRouterProvider) {
    "use strict";
    $urlRouterProvider.otherwise('/home');

    $stateProvider.state('Home', {
        url: '/home',
        templateUrl: 'views/home.html',
        data: {
            authenticate: true
        }
    }).state('Alarms', {
        url: '/alarm',
        templateUrl: 'views/alarms.html',
        controller: "AlarmController",
        data: {
            authenticate: true
        }
    }).state('AlarmSettings', {
        url: '/alarm/settings',
        templateUrl: 'views/alarm-settings.html',
        controller: "AlarmSettingsController",
        data: {
            authenticate: true
        }
    }).state('Calendar', {
        url: '/modules/calendar',
        templateUrl: 'views/modules/GCalendar.html',
        controller: "GCalendarController"
    }).state('Echonest', {
        url: '/modules/echonest',
        templateUrl: 'views/modules/echonest.html',
        controller: "EchonestController",
        data: {
            authenticate: true
        }
    }).state('Settings', {
        url: '/settings',
        templateUrl: 'views/settings.html',
        controller: "SettingsController",
        data: {
            authenticate: true
        }
    }).state('Logs', {
        url: '/settings/logs',
        templateUrl: 'views/logs.html',
        controller: "LogController",
        data: {
            authenticate: true
        }
    }).state('Music', {
        url: '/music',
        templateUrl: 'views/music.html',
        controller: "MusicController",
        data: {
            authenticate: true
        }
    }).state('Artist', {
        url: '/music/:source/artist/:id',
        templateUrl: 'views/music/artist.html',
        controller: "ArtistController",
        data: {
            authenticate: true
        }
    }).state('User', {
        url: '/user',
        templateUrl: 'views/user.html',
        controller: "UserController",
        data: {
            authenticate: true
        }
    }).state('Login', {
        url: '/login',
        templateUrl: 'views/login.html',
        controller: "UserController"
    });

}).config(function ($sceDelegateProvider) {
    'use strict';
    $sceDelegateProvider.resourceUrlWhitelist([
        // Allow same origin resource loads.
        'self',
        // Allow loading from our assets domain.  Notice the difference between * and **.
        'https://embed.spotify.com/*',
        'https://embed.spotify.com/**'
    ]);
}).run(function ($rootScope, $state, UserService) {
    'use strict';
    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
        if (toState.data && toState.data.authenticate) {
            UserService.isAuthorized(function (authorized) {
                if (!authorized) {
                    $state.transitionTo("Login");
                    event.preventDefault();
                }
            });
        }
    });
});


text:
Swinject is a lightweight dependency injection framework for Swift apps. It allows you to split your app into loosely-coupled components, which can then be maintained and tested more easily. Swinject supports pure Swift types, and is powered by the Swift generic type system and [first class functions](https://en.wikipedia.org/wiki/First-class_function). This makes it syntactically elegant and simple to define the object dependencies for your app.

## Table of Contents

### Basics

1. [DI Container](DIContainer.md)
2. [Injection Patterns](InjectionPatterns.md)
3. [Circular Dependencies](CircularDependencies.md)
4. [Object Scopes](ObjectScopes.md)
5. [Misc](Misc.md)

### Advanced Features

1. [Container Hierarchy](ContainerHierarchy.md)
2. [Properties](Properties.md)
3. [Modularizing Service Registration](Assembler.md)
4. [Thread Safety](ThreadSafety.md)

### UI Features

1. [Storyboard](Storyboard.md)

### Extensions

1. [Swinject-CodeGen](https://github.com/Swinject/Swinject-CodeGen)


text:
---
title: Database Testing
type: laravel 5.4
order: 11.4
---

## Introduction

Laravel provides a variety of helpful tools to make it easier to test your database driven applications. First, you may use the `assertDatabaseHas` helper to assert that data exists in the database matching a given set of criteria. For example, if you would like to verify that there is a record in the `users` table with the `email` value of `sally@example.com`, you can do the following:
```php
    public function testDatabase()
    {
        // Make call to application...

        $this->assertDatabaseHas('users', [
            'email' => 'sally@example.com'
        ]);
    }
```
Of course, the `assertDatabaseHas` method and other helpers like it are for convenience. You are free to use any of PHPUnit's built-in assertion methods to supplement your tests.

## Resetting The Database After Each Test

It is often useful to reset your database after each test so that data from a previous test does not interfere with subsequent tests.

### Using Migrations

One approach to resetting the database state is to rollback the database after each test and migrate it before the next test. Laravel provides a simple `DatabaseMigrations` trait that will automatically handle this for you. Simply use the trait on your test class and everything will be handled for you:

```php
    <?php

    namespace Tests\Feature;

    use Tests\TestCase;
    use Illuminate\Foundation\Testing\WithoutMiddleware;
    use Illuminate\Foundation\Testing\DatabaseMigrations;
    use Illuminate\Foundation\Testing\DatabaseTransactions;

    class ExampleTest extends TestCase
    {
        use DatabaseMigrations;

        /**
         * A basic functional test example.
         *
         * @return void
         */
        public function testBasicExample()
        {
            $response = $this->get('/');

            // ...
        }
    }
```

### Using Transactions

Another approach to resetting the database state is to wrap each test case in a database transaction. Again, Laravel provides a convenient `DatabaseTransactions` trait that will automatically handle this for you:

```php
    <?php

    namespace Tests\Feature;

    use Tests\TestCase;
    use Illuminate\Foundation\Testing\WithoutMiddleware;
    use Illuminate\Foundation\Testing\DatabaseMigrations;
    use Illuminate\Foundation\Testing\DatabaseTransactions;

    class ExampleTest extends TestCase
    {
        use DatabaseTransactions;

        /**
         * A basic functional test example.
         *
         * @return void
         */
        public function testBasicExample()
        {
            $response = $this->get('/');

            // ...
        }
    }
```

 By default, this trait will only wrap the default database connection in a transaction. If your application is using multiple database connections, you should define a `$connectionsToTransact` property on your test class. This property should be an array of connection names to execute the transactions on.

## Writing Factories

When testing, you may need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a default set of attributes for each of your [Eloquent models](/mk/laravel/eloquent.html) using model factories. To get started, take a look at the `database/factories/ModelFactory.php` file in your application. Out of the box, this file contains one factory definition:
```php
    $factory->define(App\User::class, function (Faker\Generator $faker) {
        static $password;

        return [
            'name' => $faker->name,
            'email' => $faker->unique()->safeEmail,
            'password' => $password ?: $password = bcrypt('secret'),
            'remember_token' => str_random(10),
        ];
    });
```
Within the Closure, which serves as the factory definition, you may return the default test values of all attributes on the model. The Closure will receive an instance of the [Faker](https://github.com/fzaninotto/Faker) PHP library, which allows you to conveniently generate various kinds of random data for testing.

Of course, you are free to add your own additional factories to the `ModelFactory.php` file. You may also create additional factory files for each model for better organization. For example, you could create `UserFactory.php` and `CommentFactory.php` files within your `database/factories` directory. All of the files within the `factories` directory will automatically be loaded by Laravel.

### Factory States

States allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your `User` model might have a `delinquent` state that modifies one of its default attribute values. You may define your state transformations using the `state` method:
```php
    $factory->state(App\User::class, 'delinquent', function ($faker) {
        return [
            'account_status' => 'delinquent',
        ];
    });
```

## Using Factories

### Creating Models

Once you have defined your factories, you may use the global `factory` function in your tests or seed files to generate model instances. So, let's take a look at a few examples of creating models. First, we'll use the `make` method to create models but not save them to the database:
```php
    public function testDatabase()
    {
        $user = factory(App\User::class)->make();

        // Use model in tests...
    }
```
You may also create a Collection of many models or create models of a given type:
```php
    // Create three App\User instances...
    $users = factory(App\User::class, 3)->make();
```
#### Applying States

You may also apply any of your [states](#factory-states) to the models. If you would like to apply multiple state transformations to the models, you should specify the name of each state you would like to apply:
```php
    $users = factory(App\User::class, 5)->states('delinquent')->make();

    $users = factory(App\User::class, 5)->states('premium', 'delinquent')->make();
```
#### Overriding Attributes

If you would like to override some of the default values of your models, you may pass an array of values to the `make` method. Only the specified values will be replaced while the rest of the values remain set to their default values as specified by the factory:
```php
    $user = factory(App\User::class)->make([
        'name' => 'Abigail',
    ]);
```

### Persisting Models

The `create` method not only creates the model instances but also saves them to the database using Eloquent's `save` method:
```php
    public function testDatabase()
    {
        // Create a single App\User instance...
        $user = factory(App\User::class)->create();

        // Create three App\User instances...
        $users = factory(App\User::class, 3)->create();

        // Use model in tests...
    }
```
You may override attributes on the model by passing an array to the `create` method:
```php
    $user = factory(App\User::class)->create([
        'name' => 'Abigail',
    ]);
```

### Relationships

In this example, we'll attach a relation to some created models. When using the `create` method to create multiple models, an Eloquent [collection instance](/mk/laravel/eloquent-collections.html) is returned, allowing you to use any of the convenient functions provided by the collection, such as `each`:
```php
    $users = factory(App\User::class, 3)
               ->create()
               ->each(function ($u) {
                    $u->posts()->save(factory(App\Post::class)->make());
                });
```
#### Relations & Attribute Closures

You may also attach relationships to models using Closure attributes in your factory definitions. For example, if you would like to create a new `User` instance when creating a `Post`, you may do the following:
```php
    $factory->define(App\Post::class, function ($faker) {
        return [
            'title' => $faker->title,
            'content' => $faker->paragraph,
            'user_id' => function () {
                return factory(App\User::class)->create()->id;
            }
        ];
    });
```
These Closures also receive the evaluated attribute array of the factory that defines them:
```php
    $factory->define(App\Post::class, function ($faker) {
        return [
            'title' => $faker->title,
            'content' => $faker->paragraph,
            'user_id' => function () {
                return factory(App\User::class)->create()->id;
            },
            'user_type' => function (array $post) {
                return App\User::find($post['user_id'])->type;
            }
        ];
    });
```


text:
<?php

namespace Discussione\Service;

use OldSound\RabbitMqBundle\RabbitMq\Producer;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class MessageService
{
    private $producer;

    public function __construct(Producer $producer)
    {
        $this->producer = $producer;
    }

    /**
     * @param UploadedFile $file
     */
    public function publish(UploadedFile $file)
    {
        $this->producer->publish(
            $this->encode($file)
        );
    }

    /**
     * @param UploadedFile $file
     * @return string
     */
    private function encode(UploadedFile $file)
    {
        return base64_encode(
            file_get_contents($file)
        );
    }
}


text:
#import <Cocoa/Cocoa.h>
#import "c64machinecontroller.h"

@interface C64DTVMachineController : C64MachineController
{
}

@end


text:
package git

import "github.com/essentier/nomockutil/cmd"

func CreateGitCmdRunner(projectDir string, cmdRunner cmd.CmdRunner) cmd.CmdRunner {
	return &gitCmdRunner{
		CmdRunner:  cmdRunner,
		projectDir: projectDir,
	}
}

// not safe for concurrent access
type gitCmdRunner struct {
	cmd.CmdRunner
	projectDir string
}

func (g *gitCmdRunner) RunInNewRunner(name string, args ...string) (string, cmd.CmdError) {
	return g.CmdRunner.RunInNewRunner("git", g.appendGitArgs(name, args)...)
}

func (g *gitCmdRunner) RunCmd(name string, args ...string) (string, cmd.CmdError) {
	return g.CmdRunner.RunCmd("git", g.appendGitArgs(name, args)...)
}

func (g *gitCmdRunner) appendGitArgs(name string, args []string) []string {
	return append([]string{"-C", g.projectDir, name}, args...)
}


text:
package org.appenders.log4j2.elasticsearch.ahc;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.message.ObjectMessage;
import org.appenders.log4j2.elasticsearch.BatchBuilder;
import org.appenders.log4j2.elasticsearch.GenericItemSourceLayout;
import org.appenders.log4j2.elasticsearch.ItemSource;
import org.appenders.log4j2.elasticsearch.ItemSourceFactory;
import org.appenders.log4j2.elasticsearch.JacksonSerializer;
import org.appenders.log4j2.elasticsearch.LifeCycle;
import org.appenders.log4j2.elasticsearch.PooledItemSourceFactory;
import org.appenders.log4j2.elasticsearch.PooledItemSourceFactoryTest;
import org.appenders.log4j2.elasticsearch.json.jackson.ExtendedLog4j2JsonModule;
import org.appenders.log4j2.elasticsearch.metrics.BasicMetricsRegistry;
import org.appenders.log4j2.elasticsearch.metrics.MetricsRegistry;
import org.junit.jupiter.api.Test;

import java.util.Scanner;
import java.util.UUID;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class AHCBatchOperationsTest {

    @Test
    public void throwsOnStringSource() {

        // given
        final PooledItemSourceFactory itemSourceFactory = PooledItemSourceFactoryTest.createDefaultTestSourceFactoryConfig().build();
        final AHCBatchOperations batchOperations = createDefaultBatchOperations(itemSourceFactory, null);

        final String indexName = UUID.randomUUID().toString();
        final String source = UUID.randomUUID().toString();

        // when
        final UnsupportedOperationException exception = assertThrows(UnsupportedOperationException.class, () -> batchOperations.createBatchItem(indexName, source));

        // then
        assertThat(exception.getMessage(), equalTo("Use ItemSource based API instead"));

    }

    private AHCBatchOperations createDefaultBatchOperations(final PooledItemSourceFactory itemSourceFactory) {
        return createDefaultBatchOperations(itemSourceFactory, "_doc");
    }

    private AHCBatchOperations createDefaultBatchOperations(final PooledItemSourceFactory itemSourceFactory, final String mappingType) {
        return new AHCBatchOperations(itemSourceFactory, new ElasticsearchBulkAPI(mappingType, null));
    }

    @Test
    public void createsBatchBuilder() {

        // given
        final PooledItemSourceFactory itemSourceFactory = PooledItemSourceFactoryTest.createDefaultTestSourceFactoryConfig().build();
        final BatchBuilder<BatchRequest> builder = createDefaultBatchOperations(itemSourceFactory, null).createBatchBuilder();

        // when
        final BatchRequest request = builder.build();

        // then
        assertEquals(BatchRequest.class, request.getClass());
    }

    @Test
    public void defaultWriterCanSerializeBatchRequest() throws Exception {

        // given
        final PooledItemSourceFactory<Object, ByteBuf> itemSourceFactory = PooledItemSourceFactoryTest.createDefaultTestSourceFactoryConfig().build();

        final String expectedType = UUID.randomUUID().toString();
        final AHCBatchOperations batchOperations = createDefaultBatchOperations(itemSourceFactory, expectedType);

        final GenericItemSourceLayout<Object, ByteBuf> layout = createDefaultTestLayoutBuilder(itemSourceFactory)
                .withSerializer(new JacksonSerializer.Builder<>()
                        .withJacksonModules(new ExtendedLog4j2JsonModule())
                        .build())
                .build();

        final String expectedMessage = UUID.randomUUID().toString();
        final long timeMillis = System.currentTimeMillis();
        final Log4jLogEvent logEvent = Log4jLogEvent.newBuilder()
                .setTimeMillis(timeMillis)
                .setMessage(new ObjectMessage(expectedMessage)).build();

        final ItemSource itemSource = layout.serialize(logEvent);

        final String indexName = UUID.randomUUID().toString();
        final IndexRequest indexRequest = (IndexRequest) batchOperations.createBatchItem(indexName, itemSource);

        final BatchBuilder<BatchRequest> batchBuilder = batchOperations.createBatchBuilder();
        batchBuilder.add(indexRequest);

        // when
        final ByteBuf byteBuf = (ByteBuf) batchBuilder.build().serialize().getSource();

        // then
        final Scanner scanner = new Scanner(new ByteBufInputStream(byteBuf));

        final TestIndex deserializedAction = new ObjectMapper()
                .addMixIn(TestIndex.class, IndexRequestMixIn.class)
                .readValue(scanner.nextLine(), TestIndex.class);
        assertEquals(indexName, deserializedAction.index);
        assertEquals(expectedType, deserializedAction.type);

        final TestLogEvent deserializedDocument = new ObjectMapper().readValue(scanner.nextLine(), TestLogEvent.class);
        assertEquals(timeMillis, deserializedDocument.timeMillis);
        assertNotNull(deserializedDocument.level);
        assertNotNull(deserializedDocument.thread);
        assertEquals(expectedMessage, deserializedDocument.message);

    }

    // =========
    // LIFECYCLE
    // =========

    @Test
    public void lifecycleStartStartItemSourceFactoryOnlyOnce() {

        // given
        final PooledItemSourceFactory itemSourceFactory = mock(PooledItemSourceFactory.class);
        final AHCBatchOperations batchOperations = createDefaultBatchOperations(itemSourceFactory);

        // when
        batchOperations.start();
        batchOperations.start();

        // then
        verify(itemSourceFactory).start();

    }

    @Test
    public void lifecycleStopStopsItemSourceFactoryOnlyOnce() {

        // given
        final PooledItemSourceFactory itemSourceFactory = mock(PooledItemSourceFactory.class);
        final AHCBatchOperations batchOperations = createDefaultBatchOperations(itemSourceFactory);

        batchOperations.start();

        // when
        batchOperations.stop();
        batchOperations.stop();

        // then
        verify(itemSourceFactory).stop();

    }

    @Test
    public void lifecycleStart() {

        // given
        final LifeCycle lifeCycle = createLifeCycleTestObject();

        assertTrue(lifeCycle.isStopped());

        // when
        lifeCycle.start();

        // then
        assertFalse(lifeCycle.isStopped());
        assertTrue(lifeCycle.isStarted());

    }

    @Test
    public void lifecycleStop() {

        // given
        final LifeCycle lifeCycle = createLifeCycleTestObject();

        assertTrue(lifeCycle.isStopped());

        lifeCycle.start();
        assertTrue(lifeCycle.isStarted());

        // when
        lifeCycle.stop();

        // then
        assertFalse(lifeCycle.isStarted());
        assertTrue(lifeCycle.isStopped());

    }
    // =======
    // METRICS
    // =======

    @Test
    public void registersComponentsMetrics() {

        final PooledItemSourceFactory itemSourceFactory = mock(PooledItemSourceFactory.class);
        final AHCBatchOperations batchOperations = createDefaultBatchOperations(itemSourceFactory);

        final MetricsRegistry metricsRegistry = new BasicMetricsRegistry();

        // when
        batchOperations.register(metricsRegistry);

        // then
        verify(itemSourceFactory).register(eq(metricsRegistry));

    }

    @Test
    public void deregistersComponentsMetrics() {

        // given
        final PooledItemSourceFactory itemSourceFactory = mock(PooledItemSourceFactory.class);
        final AHCBatchOperations batchOperations = createDefaultBatchOperations(itemSourceFactory);

        // when
        batchOperations.deregister();

        // then
        verify(itemSourceFactory).deregister();

    }

    private <T, R> GenericItemSourceLayout.Builder<T, R> createDefaultTestLayoutBuilder(final ItemSourceFactory<T, R> itemSourceFactory) {
        return new GenericItemSourceLayout.Builder<T, R>()
                .withItemSourceFactory(itemSourceFactory);
    }

    private LifeCycle createLifeCycleTestObject() {
        return createDefaultBatchOperations(mock(PooledItemSourceFactory.class), null);
    }

}


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/loot/tool/shared_recording_rod_broken.iff"
	result.attribute_template_id = -1
	result.stfName("item_n","recording_rod_broken")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
<!doctype HTML public "-//W3C//DTD HTML 4.0 Frameset//EN">

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Ensure Fields</title>

About
 the Ensure Fields Tool:

The Ensure Fields Tool ensures a set of fields are present in a datastream.  This is a common issue when you are reading data that changes from time to time.  If you use a Crosstab Tool or are reading from an XML file, the output fields can change based on the presence (or absence) of specific input data.  This makes it very hard to write formulas, or really do any down stream processing on those fields.  In particular, what we want to do is ensure fields are present, but NOT change them if they are already in the record.

The macro originally appeared on http://inspiringingenuity.net/2013/08/14/alteryx-ensuring-fields-are-in-a-data-stream/

Configuration Properties:

The tool has two configuration properties:

Specify a list of fields

Select the type for new fields

Version History:

Version 1.0  - As featured on http://inspiringingenuity.net.

Version 2.0 - Adopted by CRW.  Updated to CRW styling.

___________________________________________________________________________________

www.ChaosReignsWithin.com


text:
package org.jhove2.persist.berkeleydpl;

import static org.junit.Assert.*;

import java.util.List;

import javax.annotation.Resource;

import org.jhove2.core.JHOVE2;
import org.jhove2.core.JHOVE2Exception;
import org.jhove2.module.Command;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author smorrissey
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
		"classpath*:**/persist/berkeleydpl/bdb-test-config.xml",
		"classpath*:**/filepaths-config.xml"
})
public class BerkeleyDbFrameworkAccessorTest extends BerkeleyDbTestBase{

	JHOVE2 bdbJHOVE2;
	JHOVE2 localJHOVE2;
	List<Command> bdbCommands;

	/**
	 * Test method for {@link org.jhove2.persist.berkeleydpl.BerkeleyDbBaseModuleAccessor#persistModule(org.jhove2.module.Module)}.
	 */
	@Test
	public void testPersistModule() {
		try {
			localJHOVE2 = new JHOVE2(new BerkeleyDbFrameworkAccessor());
			assertNull(localJHOVE2.getModuleId());
			localJHOVE2 = (JHOVE2) localJHOVE2.getModuleAccessor().persistModule(localJHOVE2);
			assertNotNull(localJHOVE2.getModuleId());
		} catch (JHOVE2Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Test method for {@link org.jhove2.persist.berkeleydpl.BerkeleyDbFrameworkAccessor#getCommands(org.jhove2.core.JHOVE2)}.
	 */
	@Test
	public void testGetCommands() {
		try {
			BerkeleyDbFrameworkAccessor accessor = new BerkeleyDbFrameworkAccessor();
			localJHOVE2 = new JHOVE2(accessor);
			List<Command> commands = accessor.getCommands(localJHOVE2);
			assertEquals(0,commands.size());
			assertNotNull(localJHOVE2.getModuleId());
			long localId = localJHOVE2.getModuleId().longValue();
			localJHOVE2 = (JHOVE2) localJHOVE2.getModuleAccessor().persistModule(localJHOVE2);
			assertEquals(localId, localJHOVE2.getModuleId().longValue());

		} catch (JHOVE2Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Test method for {@link org.jhove2.persist.berkeleydpl.BerkeleyDbFrameworkAccessor#setCommands(org.jhove2.core.JHOVE2, java.util.List)}.
	 */
	@Test
	public void testSetCommands() {
		assertNotNull(bdbJHOVE2.getModuleId());
		long longVal =  bdbJHOVE2.getModuleId().longValue();
		BerkeleyDbFrameworkAccessor accessor = (BerkeleyDbFrameworkAccessor) bdbJHOVE2.getModuleAccessor();
		try {
			List<Command> commands = accessor.getCommands(bdbJHOVE2);
			assertEquals(3, commands.size());
			bdbJHOVE2 = (JHOVE2) bdbJHOVE2.getModuleAccessor().persistModule(bdbJHOVE2);
			assertNotNull(bdbJHOVE2.getModuleId());
			longVal =  bdbJHOVE2.getModuleId().longValue();
			List<Command> newCommands  = accessor.setCommands(bdbJHOVE2, null);
			assertEquals(0, newCommands.size());
			for (Command command:commands){
				assertEquals(longVal, command.getJhove2ModuleId().longValue());
				BerkeleyDbCommandAccessor ma = (BerkeleyDbCommandAccessor)command.getModuleAccessor();
				command = (Command) ma.retrieveModule(command.getModuleId());
				assertNull(command.getJhove2ModuleId());

			}
		} catch (JHOVE2Exception e) {
			e.printStackTrace();
		}

	}
	/**
	 * @param bdbJHOVE2 the bdbJHOVE2 to set
	 */
	@Resource
	public void setBdbJHOVE2(JHOVE2 bdbJHOVE2) {
		this.bdbJHOVE2 = bdbJHOVE2;
	}

}