text:
package org.ovirt.engine.core.bll.storage;

import static org.ovirt.engine.core.common.businessentities.NonOperationalReason.STORAGE_DOMAIN_UNREACHABLE;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import org.ovirt.engine.core.bll.IsoDomainListSyncronizer;
import org.ovirt.engine.core.bll.LockMessagesMatchUtil;
import org.ovirt.engine.core.bll.NonTransactiveCommandAttribute;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.job.ExecutionHandler;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.LockProperties;
import org.ovirt.engine.core.common.action.LockProperties.Scope;
import org.ovirt.engine.core.common.action.SetNonOperationalVdsParameters;
import org.ovirt.engine.core.common.action.StorageDomainPoolParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMap;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMapId;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.eventqueue.Event;
import org.ovirt.engine.core.common.eventqueue.EventQueue;
import org.ovirt.engine.core.common.eventqueue.EventResult;
import org.ovirt.engine.core.common.eventqueue.EventType;
import org.ovirt.engine.core.common.locks.LockingGroup;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.ActivateStorageDomainVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.TransactionScopeOption;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.ejb.BeanProxyType;
import org.ovirt.engine.core.utils.ejb.BeanType;
import org.ovirt.engine.core.utils.ejb.EjbUtils;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;

@NonTransactiveCommandAttribute(forceCompensation=true)
public class ActivateStorageDomainCommand<T extends StorageDomainPoolParametersBase> extends
        StorageDomainCommandBase<T> {

    public ActivateStorageDomainCommand(T parameters) {
        this(parameters, null);
    }

    public ActivateStorageDomainCommand(T parameters, CommandContext commandContext) {
        super(parameters, commandContext);
    }

    @Override
    protected LockProperties applyLockProperties(LockProperties lockProperties) {
        return lockProperties.withScope(Scope.Execution);
    }

    /**
     * Constructor for command creation when compensation is applied on startup
     *
     * @param commandId
     */
    protected ActivateStorageDomainCommand(Guid commandId) {
        super(commandId);
    }

    @Override
    protected boolean canDoAction() {
        boolean returnValue = checkStoragePool()
                && checkStoragePoolStatusNotEqual(StoragePoolStatus.Uninitialized,
                VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_STATUS_ILLEGAL)
                && checkStorageDomain()
                && storageDomainStatusIsValid()
                && (getStorageDomain().getStorageDomainType() == StorageDomainType.Master || checkMasterDomainIsUp())
                && checkForActiveVds() != null;
        return returnValue;
    }

    @Override
    protected void executeCommand() {
        final StoragePoolIsoMap map =
                DbFacade.getInstance()
                        .getStoragePoolIsoMapDao()
                        .get(new StoragePoolIsoMapId(getParameters().getStorageDomainId(),
                                getParameters().getStoragePoolId()));
        // Master domain must not go through the Activating status.
        changeStorageDomainStatusInTransaction(map,
                (getStorageDomain().getStorageDomainType() == StorageDomainType.Master) ?
                    StorageDomainStatus.Locked : StorageDomainStatus.Activating);
        freeLock();

        log.infoFormat("ActivateStorage Domain. Before Connect all hosts to pool. Time:{0}", new Date());
        connectAllHostsToPool();
        runVdsCommand(VDSCommandType.ActivateStorageDomain,
                new ActivateStorageDomainVDSCommandParameters(getStoragePool().getId(), getStorageDomain().getId()));
        log.infoFormat("ActivateStorage Domain. After Connect all hosts to pool. Time:{0}", new Date());

        TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
            @Override
            public Void runInTransaction() {
                map.setStatus(StorageDomainStatus.Active);
                DbFacade.getInstance().getStoragePoolIsoMapDao().updateStatus(map.getId(), map.getStatus());
                if (getStorageDomain().getStorageDomainType() == StorageDomainType.Master) {
                    calcStoragePoolStatusByDomainsStatus();
                }
                return null;
            }
        });
        refreshAllVdssInPool();

        log.infoFormat("ActivateStorage Domain. After change storage pool status in vds. Time:{0}",
                new Date());
        if (getStorageDomain().getStorageDomainType() == StorageDomainType.ISO) {
            IsoDomainListSyncronizer.getInstance().refresheIsoDomainWhenActivateDomain(getStorageDomain().getId(),
                    getStoragePool().getId());
        }
        setSucceeded(true);
    }

    private void refreshAllVdssInPool() {
        final List<Guid> vdsIdsToSetNonOperational = new ArrayList<Guid>();

        ((EventQueue) EjbUtils.findBean(BeanType.EVENTQUEUE_MANAGER, BeanProxyType.LOCAL)).submitEventSync(
                new Event(getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), null, EventType.POOLREFRESH, ""),
                new Callable<EventResult>() {
                    @Override
                    public EventResult call() {
                        runSynchronizeOperation(new RefreshPoolSingleAsyncOperationFactory(), vdsIdsToSetNonOperational);
                        return null;
                    }
                }
        );

        for (Guid vdsId : vdsIdsToSetNonOperational) {
            Map<String, String> customLogValues = Collections.singletonMap("StorageDomainNames", getStorageDomainName());
            SetNonOperationalVdsParameters tempVar =
                    new SetNonOperationalVdsParameters(vdsId, STORAGE_DOMAIN_UNREACHABLE, customLogValues);
            tempVar.setStorageDomainId(getStorageDomain().getId());
            tempVar.setTransactionScopeOption(TransactionScopeOption.RequiresNew);
            runInternalAction(VdcActionType.SetNonOperationalVds,
                    tempVar,
                    ExecutionHandler.createInternalJobContext(getContext()));
        }
    }

    @Override
    public AuditLogType getAuditLogTypeValue() {
        if (getParameters().isRunSilent()) {
            return getSucceeded() ? AuditLogType.USER_ACTIVATED_STORAGE_DOMAIN_ASYNC
                    : AuditLogType.USER_ACTIVATE_STORAGE_DOMAIN_FAILED_ASYNC;
        }
        return getSucceeded() ? AuditLogType.USER_ACTIVATED_STORAGE_DOMAIN
                : AuditLogType.USER_ACTIVATE_STORAGE_DOMAIN_FAILED;
    }

    @Override
    protected Map<String, Pair<String, String>> getExclusiveLocks() {
        return Collections.singletonMap(getStorageDomainId().toString(),
                LockMessagesMatchUtil.makeLockingPair(LockingGroup.STORAGE, VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED));
    }

    @Override
    protected void setActionMessageParameters() {
        addCanDoActionMessage(VdcBllMessages.VAR__TYPE__STORAGE__DOMAIN);
        addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ACTIVATE);
    }

    private boolean storageDomainStatusIsValid() {
        boolean returnValue;
        if (isInternalExecution()) {
            returnValue = checkStorageDomainStatus(StorageDomainStatus.Inactive, StorageDomainStatus.Unknown,
                    StorageDomainStatus.Locked, StorageDomainStatus.Maintenance,
                    StorageDomainStatus.PreparingForMaintenance);
        } else {
            returnValue = checkStorageDomainStatus(StorageDomainStatus.Inactive, StorageDomainStatus.Unknown,
                    StorageDomainStatus.Maintenance, StorageDomainStatus.PreparingForMaintenance);
        }
        return returnValue;
    }
}


text:
Vtiger_BasicSearch_Js("Vtiger_AdvanceSearch_Js",{

	//cache will store the search data
	cache : {}

},{
	//container which will store the search elements
	elementContainer : false,
	//instance which represents advance filter
	advanceFilter : false,

	//states whether the validation is registred for filter elements
	filterValidationRegistered : false,

	//contains the filter form element
	filterForm : false,

	/**
	 * Function which will give the container
	 */
	getContainer : function() {
		return this.elementContainer;
	},

	/**
	 *Function which is used to set the continaer
	 *@params : container - element which represent the container
	 *@return current instance
	 */
	setContainer : function(container) {
		this.elementContainer = container;
		return this;
	},

	getFilterForm : function() {
		return jQuery('form[name="advanceFilterForm"]',this.getContainer());
	},

	/**
	 * Function used to get the advance search ui
	 * @return : deferred promise
	 */
	getAdvanceSearch : function() {
		var aDeferred = jQuery.Deferred();
		var moduleName = app.getModuleName();
		var searchModule = this.getSearchModule();

		//Exists in the cache
		if(searchModule in Vtiger_AdvanceSearch_Js.cache) {
			aDeferred.resolve(Vtiger_AdvanceSearch_Js.cache[searchModule]);
			return aDeferred.promise();
		}

        //if you are in settings then module should be vtiger
        if(app.getParentModuleName().length > 0) {
            moduleName = 'Vtiger';
        }

        var searchableModulesParams = {
			"module":moduleName,
			"view"	: "BasicAjax",
			"mode"	: "showAdvancedSearch",
			"source_module": searchModule
        };

		var progressInstance = jQuery.progressIndicator();
		AppConnector.request(searchableModulesParams).then(
			function(data){
				progressInstance.hide();
				//add to cache
				Vtiger_AdvanceSearch_Js.cache[searchModule] = data;
				aDeferred.resolve(data);
			},
			function(error,err){
				aDeferred.reject(error);
			}
		);
		return aDeferred.promise();
	},

	/**
	 * Function which intializes search
	 */
	initiateSearch : function() {
        var aDeferred = jQuery.Deferred();
		var thisInstance = this;
		var postLoad = function(uiData) {
			thisInstance.setContainer(jQuery('#advanceSearchContainer'));
			thisInstance.registerEvents();
			thisInstance.advanceFilter = new Vtiger_SearchAdvanceFilter_Js(jQuery('.filterContainer',uiData));
			//align it below the search element
			uiData.closest('.blockMsg').position({
				my: "left bottom",
				at: "left bottom",
				of: "#globalSearchValue",
				offset: "1 -29"
			});
            aDeferred.resolve();
		}

		this.getAdvanceSearch().then(
			function(data){
				var params = {};
				params.data = data ;
				params.cb = postLoad;
				//TODO : put this css as attribute of object so that its easy for maintanace
				params.css = {'width':'50%','text-align':'left','background-color':'transparent','border-width':'0px'};
				//not showing overlay
				params.overlayCss = {'opacity':'0.2'};

				app.showModalWindow(params);

			},
			function(error) {
                aDeferred.reject();
			}
		)
        return aDeferred.promise();
	},

    getNameFields : function() {
        var form = this.getFilterForm();
        return form.find('[name="labelFields"]').data('value');
    },

    selectBasicSearchValue : function() {
      var value = jQuery('#globalSearchValue').val();
      if(value.length > 0 ) {
          var form = this.getFilterForm();
          var labelFieldList = this.getNameFields();
          if(typeof labelFieldList == 'undefined' || labelFieldList.length == 0) {
              return;
          }
          var anyConditionContainer = form.find('.anyConditionContainer');
          for(var index in labelFieldList){
            var labelFieldName = labelFieldList[index];
            if(index !=0 ) {
                //By default one condition exits , only if you have multiple label fields you have add one more condition
                anyConditionContainer.find('.addCondition').find('button').trigger('click');
            }
            var conditionRow = anyConditionContainer.find('.conditionList').find('.conditionRow:last');
            var fieldSelectElemnt = conditionRow.find('select[name="columnname"]');
            fieldSelectElemnt.find('option[data-field-name="'+ labelFieldName +'"]').attr('selected','selected');
            fieldSelectElemnt.trigger('change').trigger('liszt:updated');

            var comparatorSelectElemnt = conditionRow.find('select[name="comparator"]');
            //select the contains value
            comparatorSelectElemnt.find('option[value="c"]').attr('selected','selected');
            comparatorSelectElemnt.trigger('liszt:updated');

            var valueElement = conditionRow.find('[name="value"]');
            valueElement.val(value);
          }

      }
    },

	/**
	 * Function which invokes search
	 */
	search : function() {
		var conditionValues = this.advanceFilter.getValues();
		var module = this.getSearchModule();

		var params = {};
		params.module = module;
		params.advfilterlist = JSON.stringify(conditionValues);

		return this._search(params);
	},

	/**
	 * Function which shows search results in proper manner
	 * @params : data to be shown
	 */
	showSearchResults : function(data){
		var thisInstance = this;
		var aDeferred = jQuery.Deferred();
		var postLoad = function(data) {
			var blockMsg = jQuery(data).closest('.blockMsg');
			app.showScrollBar(jQuery(data).find('.contents'));
			aDeferred.resolve(data);
		}

		var unblockcd = function(){
			thisInstance.getContainer().remove();
		}

		var html = '
'+
						''+
						''+
					'
';
		var jQhtml = jQuery(html);
		jQuery('.searchHolder',jQhtml).html(data);

		data = jQhtml;

		var params = {};
		params.data = data;
		params.cb = postLoad;
		params.css = {'width':'23%','text-align':'left'};
		params.overlayCss = {'opacity':'0.2'};
		params.unblockcb = unblockcd;
		app.showModalWindow(params);

		return aDeferred.promise();
	},

	/**
	 * Function which will save the filter
	 */
	saveFilter : function(params) {
		var aDeferred = jQuery.Deferred();
		params.source_module = this.getSearchModule();
		params.status = 1;
		params.advfilterlist = JSON.stringify(this.advanceFilter.getValues(false));

		params.module = 'CustomView';
		params.action = 'Save';

		AppConnector.request(params).then(function(data){
			aDeferred.resolve(data);
		})
		return aDeferred.promise();
	},

	/**
	 * Function which will save the filter and show the list view of new custom view
	 */
	saveAndViewFilter : function(params){
		this.saveFilter(params).then(
			function(response){
				var url = response['result']['listviewurl'];
				window.location.href=url;
			},
			function(error) {

			}
		);
	},

	/**
	 * Function which specify whether the search component and filter component both are shown
	 */
	isSearchAndFilterComponentsShown : function() {
		var modalData = jQuery('#globalmodal');
		var filterComponent = jQuery('.filterHolder',modalData).find('#advanceSearchContainer');
		if(filterComponent.length <= 0 ) {
			return false;
		}
		return true;
	},

	/**
	 * Function which will perform search and other operaions
	 */
	performSearch : function() {
		var thisInstance = this;
		var isSearchResultsAndFilterShown = this.isSearchAndFilterComponentsShown();
		this.search().then(function(data){
			thisInstance.setContainer(thisInstance.getContainer().detach());
			thisInstance.showSearchResults(data).then(function(modalBlock){
				var msgContainer = modalBlock.closest('.blockMsg');
				msgContainer.position({
					my: "left bottom",
					at: "left bottom",
					of: "#globalSearchValue",
					offset: "1 -29"
				});
				thisInstance.registerShowFiler();
				//if the filter already shown , show again
				if(isSearchResultsAndFilterShown) {
					thisInstance.showFilter();
				}
			});

		});
	},

	/**
	 * Function which will show the advance filter next to search results
	 */
	showFilter : function(){
		var modalData = jQuery('#globalmodal');

		var searchHolder = jQuery('.searchHolder', modalData);
		var filterHolder = jQuery('.filterHolder', modalData);
		filterHolder.removeClass('hide').html(this.getContainer());
		searchHolder.removeClass('col-md-12').addClass('col-md-4');
		modalData.closest('.blockMsg').css('width' , '73%');
	},

	/**
	 * Function which will perform the validation for the advance filter fields
	 * @return : deferred promise - resolves if validation succeded if not failure
	 */
	performValidation : function() {
		var thisInstance = this;
		this.formValidationDeferred = jQuery.Deferred();
		var controlForm = this.getFilterForm();

		var validationDone = function(form, status){
			if(status) {
				thisInstance.formValidationDeferred.resolve();
			}else{
				thisInstance.formValidationDeferred.reject();
			}
		}
		//To perform validation registration only once
		if(!this.filterValidationRegistered){
			this.filterValidationRegistered = true;
			controlForm.validationEngine({
				'onValidationComplete' : validationDone
			});
		}
		//This will trigger the validation
		controlForm.submit();
		return this.formValidationDeferred.promise();
	},

	/**
	 * Function which will register the show filer invocation
	 */
	registerShowFiler : function() {
		var thisInstance = this;
		jQuery('#showFilter').on('click',function(e){
			thisInstance.showFilter();
		});
	},

	/**
	 * Function which will register events
	 */
	registerEvents : function() {
		var thisInstance = this;
		var container = this.getContainer();

		container.on('change','#searchModuleList', function(e){
			var selectElement = jQuery(e.currentTarget);
			var selectedModuleName = selectElement.val();

			thisInstance.setSearchModule(selectedModuleName);

			thisInstance.initiateSearch().then(function(){
                thisInstance.selectBasicSearchValue();
            });
		});

		jQuery('#advanceSearchButton').on('click', function(e){
			var searchModule = thisInstance.getSearchModule();
			//If no module is selected
			if(searchModule.length <= 0) {
				app.getChosenElementFromSelect(jQuery('#searchModuleList'))
						.validationEngine('showPrompt', app.vtranslate('JS_SELECT_MODULE'), 'error','topRight',true)
				return;
			}
			thisInstance.performValidation().then(
				function(){
					 thisInstance.performSearch();
				},
				function(){

				}
			);
		});

		jQuery('#advanceIntiateSave').on('click', function(e){
			var currentElement = jQuery(e.currentTarget);
			currentElement.addClass('hide');
			var actionsContainer = currentElement.closest('.actions');
			jQuery('input[name="viewname"]',actionsContainer).removeClass('zeroOpacity').focus();
			jQuery('#advanceSave').removeClass('hide');
		});

		jQuery('#advanceSave').on('click',function(e){
			var actionsContainer = jQuery(e.currentTarget).closest('.actions');
			var filterNameField = jQuery('input[name="viewname"]',actionsContainer);
			var value = filterNameField.val();
			if(value.length <= 0) {
				filterNameField.validationEngine('showPrompt', app.vtranslate('JS_REQUIRED'), 'error','topRight',true);
				return;
			}

			var searchModule = thisInstance.getSearchModule();
			//If no module is selected
			if(searchModule.length <= 0) {
				app.getChosenElementFromSelect(jQuery('#searchModuleList'))
						.validationEngine('showPrompt', app.vtranslate('JS_SELECT_MODULE'), 'error','topRight',true)
				return;
			}

			thisInstance.performValidation().then(function(){
				var params = {};
				params.viewname = value;
				thisInstance.saveAndViewFilter(params);
			});
		});

		//DO nothing on submit of filter form
		this.getFilterForm().on('submit',function(e){
			e.preventDefault();
		})

		//To set the search module with the currently selected values.
		this.setSearchModule(jQuery('#searchModuleList').val());
	}
})

redpajama_set_name: RedPajamaGithub


text:
package com.comcast.money.core.async

import com.comcast.money.core.SpecHelpers
import com.comcast.money.core.concurrent.ConcurrentSupport
import com.typesafe.config.ConfigFactory
import org.mockito.ArgumentMatchers._
import org.mockito.Mockito._

import scala.concurrent.Future
import org.scalatest.wordspec.AnyWordSpec
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.matchers.should.Matchers
import org.scalatest.OneInstancePerTest

class AsyncNotifierSpec
  extends AnyWordSpec
  with MockitoSugar with Matchers with ConcurrentSupport with OneInstancePerTest with SpecHelpers {

  "AsyncNotifier" should {
    "create a sequence of AsyncNotificationServices" in {
      val config = ConfigFactory.parseString(
        """
          |{
          | handlers = [
          |   {
          |     class = "com.comcast.money.core.async.NonConfiguredNotificationHandler"
          |   },
          |   {
          |     class = "com.comcast.money.core.async.NonConfiguredNotificationHandler"
          |   }
          | ]
          |}
        """.stripMargin)

      val result = AsyncNotifier(config)
      result shouldBe a[AsyncNotifier]
      result.handlers.size shouldBe 2
    }
    "configures an AsyncNotificationHandler that implements ConfigurableNotificationHandler" in {
      val config = ConfigFactory.parseString(
        """
          |{
          | handlers = [
          |   {
          |     class = "com.comcast.money.core.async.NonConfiguredNotificationHandler"
          |   },
          |   {
          |     class = "com.comcast.money.core.async.ConfiguredNotificationHandler"
          |   }
          | ]
          |}
        """.stripMargin)

      val result = AsyncNotifier(config)
      result shouldBe a[AsyncNotifier]
      result.handlers.size shouldBe 2

      result.handlers.head shouldBe a[NonConfiguredNotificationHandler]
      result.handlers.last shouldBe a[ConfiguredNotificationHandler]

      result.handlers.last.asInstanceOf[ConfiguredNotificationHandler].calledConfigure shouldBe true
    }
    "find AsyncNotificationHandler that supports Future" in {
      val mockHandler = mock[AsyncNotificationHandler]
      val futureClass = classOf[Future[_]]
      val future = mock[Future[String]]

      val asyncNotifier = AsyncNotifier(Seq(mockHandler))
      when(mockHandler.supports(futureClass, future)).thenReturn(true)

      val result = asyncNotifier.resolveHandler(futureClass, future)

      verify(mockHandler, times(1)).supports(futureClass, future)

      result.isDefined shouldEqual true
      result.get shouldEqual mockHandler
    }
    "not find any AsyncNotificationHandler for null futureClass" in {
      val mockHandler = mock[AsyncNotificationHandler]
      val future = mock[Future[String]]

      val asyncNotifier = AsyncNotifier(Seq(mockHandler))
      when(mockHandler.supports(any[Class[_]], any)).thenReturn(true)

      val result = asyncNotifier.resolveHandler(null, future)

      result.isEmpty shouldEqual true
      verify(mockHandler, never).supports(any[Class[_]], any)
    }
    "not find any AsyncNotificationHandler for null future" in {
      val mockHandler = mock[AsyncNotificationHandler]

      val asyncNotifier = AsyncNotifier(Seq(mockHandler))
      when(mockHandler.supports(any[Class[_]], any)).thenReturn(true)

      val result = asyncNotifier.resolveHandler(classOf[Future[_]], null)

      result.isEmpty shouldEqual true
      verify(mockHandler, never).supports(any[Class[_]], any)
    }
    "not find AsyncNotificationHandler when not supported" in {
      val mockHandler = mock[AsyncNotificationHandler]

      val asyncNotifier = AsyncNotifier(Seq(mockHandler))
      when(mockHandler.supports(any[Class[_]], any)).thenReturn(false)

      val result = asyncNotifier.resolveHandler(classOf[Future[_]], new Object)

      result.isEmpty shouldEqual true
      verify(mockHandler, times(1)).supports(any[Class[_]], any)
    }
  }
}


text:
<?php
$params = [];
$params['migrationAliases'] = [];
{% if advanced == true %}
$params['migrationAliases'][] = '@canis/db/migrations';
{% endif %}
$params['migrationAliases'][] = '{{ namespaceAlias }}/migrations';
return $params;


text:
using System;

namespace MaxMind.Db
{
    internal interface IByteReader : IDisposable
    {
        int Length { get; }

        byte[] Read(int offset, int count);

        byte ReadOne(int offset);

        void Copy(int offset, byte[] array);
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.05.16 at 02:08:28 PM EDT
//

package org.kitfox.stm.v1;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Erreur" maxOccurs="unbounded">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="Code" type="{http://www.w3.org/2001/XMLSchema}token"/>
 *                   <element name="Description" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *         <element name="Sommaire" type="{http://www.w3.org/2001/XMLSchema}token"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "erreur",
    "sommaire"
})
@XmlRootElement(name = "Erreurs")
public class Erreurs {

    @XmlElement(name = "Erreur", required = true)
    protected List<Erreur> erreur;
    @XmlElement(name = "Sommaire", required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "token")
    protected String sommaire;

    /**
     * Gets the value of the erreur property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the erreur property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getErreur().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Erreur }
     *
     *
     */
    public List<Erreur> getErreur() {
        if (erreur == null) {
            erreur = new ArrayList<Erreur>();
        }
        return this.erreur;
    }

    /**
     * Gets the value of the sommaire property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSommaire() {
        return sommaire;
    }

    /**
     * Sets the value of the sommaire property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSommaire(String value) {
        this.sommaire = value;
    }

}


text:
<title> / linq.sql.tokens.WhitespaceToken.IsStringLiteral</title>
<link rel="stylesheet" href="..\..\style.css">

linq.sql.tokens / WhitespaceToken / IsStringLiteral

IsStringLiteral

fun IsStringLiteral(token: Token): Boolean

Overrides Token.IsStringLiteral

Returns whether the Token is a string literal i.e "Hello"

Parameters

token - the Token to check

Return

whether the Token is a string literal


text:
Home

Archives

Tags

RSS

        <form action="//www.google.com.hk/search" method="get" accept-charset="UTF-8" id="search">
            <input type="hidden" name="sitesearch" value="{{ .Site.BaseURL }}" />
            <input type="text" name="q" results="0" placeholder="Search..." x-webkit-speech />
        </form>


text:
package the.internet.app;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;

import com.test.utils.Utility;

public class TheInternateBase {

  public static WebDriver driver;
  public static Utility utility;

  @BeforeSuite
  public void beforeSuite() {
    String BROWSER = System.getProperty("browser", "firefox");
    System.out.println("BROWSER >>>>>> " + System.getProperty("browser"));
    if (BROWSER.equals("firefox")) {
      driver = new FirefoxDriver();
    } else if (BROWSER.equals("chrome")) {
      String path = "lib/chromedriver";
      if (System.getProperty("os.name").contains("Windows")) {
        path = "lib/chromedriver.exe";
      }
      System.setProperty("webdriver.chrome.driver", path);
      driver = new ChromeDriver();
    } else if (BROWSER.equals("ie")) {
      DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
      capabilities
          .setCapability(
              InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
              true);
      String path = "lib/IEDriverServer.exe";
      System.setProperty("webdriver.ie.driver", path);
      driver = new InternetExplorerDriver();
    } else {
      throw new RuntimeException("Browser type unsupported");
    }
    driver.get("http://the-internet.herokuapp.com/");
    driver.manage().window().maximize();
    utility = new Utility(driver);
  }

  @AfterSuite
  public void afterSuite() {
    // close browser
    driver.quit();
  }

  protected static WebDriver getDriver() {
    return driver;
  }

  protected static Utility getUtility() {
    return utility;
  }
}


text:
package com.gs.obevo.impl;

import com.gs.obevo.api.platform.CommandExecutionContext;

/**
 * Strategy interface for controlling how change deployments should get done, notably around whether certain differences
 * are allowed or whether to execute them.
 */
public interface DeployStrategy {
    String getDeployVerbMessage();

    void deploy(ChangeTypeBehaviorRegistry changeTypeBehaviorRegistry, ExecuteChangeCommand changeCommand, CommandExecutionContext cec);

    boolean isInitAllowedOnHashExceptions();
}


text:
package com.xxfff.core.model;

import java.util.List;
import java.util.Map;

public class Pager<T> {

	// 分页结果集
	private List<T> dataList = null;

	private Map<String, Object> map = null;

	// 记录总数
	private int totalCount = 0;

	// 每页显示记录数
	private int pageSize = 0;

	// 当前页数
	private int currentPage = 1;

	private int pageCount = 1;

	/* 初始化分页组件 */
	public Pager(Integer pageSize, Integer totalCount,Integer currentPage) {

		if(null==pageSize){
			pageSize = 10;
		}

		setPageSize(pageSize);

		if(null == totalCount){
			totalCount = 0;
		}

		setTotalCount(totalCount);

		Double pageNum=Math.ceil((getTotalCount()+0.00)/pageSize);

		if(null==currentPage||currentPage<1||totalCount==0){

			setCurrentPage(1);

		}else if(currentPage>pageNum.intValue()){

			setCurrentPage(pageNum.intValue());

		}else{

			setCurrentPage(currentPage);

		}

		setPageCount(pageNum.intValue());

	}

	public Pager(int totalCount, int pageSize, int currentPage,List<T> dataList) {
		this.dataList = dataList;
		this.pageSize = pageSize;
		this.currentPage = currentPage;
		this.totalCount = totalCount;
	}

	public Pager(Pager pager) {
		pageSize = pager.getPageSize();
		currentPage = pager.getCurrentPage();
		totalCount = pager.getTotalCount();
	}

	public Pager() {
	}

	public boolean isLastPage(){
		return ((this.getCurrentPage() + 1) * this.getPageSize()) >= this.getPageCount();
	}

	public List<T> getDataList() {
		return dataList;
	}

	public void setDataList(List<T> dataList) {
		this.dataList = dataList;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	// 计算总页数,如果为0则置为1
	public int getPageCount() {

		return pageCount ;

	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	/**
	 * FunName:    	    updatePageCount
	 * Description :   	更新总页数
	 * @Author:         袁鹏(Jeek)
	 * @Create Date: 	2013年9月17日 下午2:31:36
	 */
	public void updatePageCount() {
		if(totalCount == 0){
			this.pageCount = 0;
		}else{
			this.pageCount = (totalCount - 1)/this.pageSize;
		}
	}

	public Map<String, Object> getMap() {
		return map;
	}

	public void setMap(Map<String, Object> map) {
		this.map = map;
	}
}


text:
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JSBase.h>

@class DOMDocument;
@class DOMHTMLElement;
@class JSContext;
@class NSURLRequest;
@class WebArchive;
@class WebDataSource;
@class WebFramePrivate;
@class WebFrameView;
@class WebScriptObject;
@class WebView;

/*!
    @class WebFrame
    @discussion Every web page is represented by at least one WebFrame.  A WebFrame
    has a WebFrameView and a WebDataSource.
*/
@interface WebFrame : NSObject
{
@package
    WebFramePrivate *_private;
}

/*!
    @method initWithName:webFrameView:webView:
    @abstract The designated initializer of WebFrame.
    @discussion WebFrames are normally created for you by the WebView.  You should
    not need to invoke this method directly.
    @param name The name of the frame.
    @param view The WebFrameView for the frame.
    @param webView The WebView that manages the frame.
    @result Returns an initialized WebFrame.
*/
- (instancetype)initWithName:(NSString *)name webFrameView:(WebFrameView *)view webView:(WebView *)webView;

/*!
    @property name
    @abstract The frame name.
*/
@property (nonatomic, readonly, copy) NSString *name;

/*!
    @property webView
    @abstract The WebView for the document that includes this frame.
*/
@property (nonatomic, readonly, strong) WebView *webView;

/*!
    @property frameView
    @abstract The WebFrameView for this frame.
*/
@property (nonatomic, readonly, strong) WebFrameView *frameView;

/*!
    @property DOMDocument
    @abstract The DOM document of the frame.
    @description Returns nil if the frame does not contain a DOM document such as a standalone image.
*/
@property (nonatomic, readonly, strong) DOMDocument *DOMDocument;

/*!
    @property frameElement
    @abstract The frame element of the frame.
    @description The class of the result is either DOMHTMLFrameElement, DOMHTMLIFrameElement or DOMHTMLObjectElement.
    Returns nil if the frame is the main frame since there is no frame element for the frame in this case.
*/
@property (nonatomic, readonly, strong) DOMHTMLElement *frameElement;

/*!
    @method loadRequest:
    @param request The web request to load.
*/
- (void)loadRequest:(NSURLRequest *)request;

/*!
    @method loadData:MIMEType:textEncodingName:baseURL:
    @param data The data to use for the main page of the document.
    @param MIMEType The MIME type of the data.
    @param encodingName The encoding of the data.
    @param URL The base URL to apply to relative URLs within the document.
*/
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)URL;

/*!
    @method loadHTMLString:baseURL:
    @param string The string to use for the main page of the document.
    @param URL The base URL to apply to relative URLs within the document.
*/
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)URL;

/*!
    @method loadAlternateHTMLString:baseURL:forUnreachableURL:
    @abstract Loads a page to display as a substitute for a URL that could not be reached.
    @discussion This allows clients to display page-loading errors in the webview itself.
    This is typically called while processing the WebFrameLoadDelegate method
    -webView:didFailProvisionalLoadWithError:forFrame: or one of the the WebPolicyDelegate methods
    -webView:decidePolicyForMIMEType:request:frame:decisionListener: or
    -webView:unableToImplementPolicyWithError:frame:. If it is called from within one of those
    three delegate methods then the back/forward list will be maintained appropriately.
    @param string The string to use for the main page of the document.
    @param baseURL The baseURL to apply to relative URLs within the document.
    @param unreachableURL The URL for which this page will serve as alternate content.
*/
- (void)loadAlternateHTMLString:(NSString *)string baseURL:(NSURL *)baseURL forUnreachableURL:(NSURL *)unreachableURL;

/*!
    @method loadArchive:
    @abstract Causes WebFrame to load a WebArchive.
    @param archive The archive to be loaded.
*/
- (void)loadArchive:(WebArchive *)archive;

/*!
    @property dataSource
    @abstract The datasource for this frame.
    @discussion Returns the committed data source.  Will return nil if the
    provisional data source hasn't yet been loaded.
*/
@property (nonatomic, readonly, strong) WebDataSource *dataSource;

/*!
    @property provisionalDataSource
    @abstract The provisional datasource of this frame.
    @discussion Will return the provisional data source.  The provisional data source will
    be nil if no data source has been set on the frame, or the data source
    has successfully transitioned to the committed data source.
*/
@property (nonatomic, readonly, strong) WebDataSource *provisionalDataSource;

/*!
    @method stopLoading
    @discussion Stop any pending loads on the frame's data source,
    and its children.
*/
- (void)stopLoading;

/*!
    @method reload
    @discussion Performs HTTP/1.1 end-to-end revalidation using cache-validating conditionals if possible.
*/
- (void)reload;

/*!
    @method reloadFromOrigin
    @discussion Performs HTTP/1.1 end-to-end reload.
*/
- (void)reloadFromOrigin;

/*!
    @method findFrameNamed:
    @discussion This method returns a frame with the given name. findFrameNamed returns self
    for _self and _current, the parent frame for _parent and the main frame for _top.
    findFrameNamed returns self for _parent and _top if the receiver is the mainFrame.
    findFrameNamed first searches from the current frame to all descending frames then the
    rest of the frames in the WebView. If still not found, findFrameNamed searches the
    frames of the other WebViews.
    @param name The name of the frame to find.
    @result The frame matching the provided name. nil if the frame is not found.
*/
- (WebFrame *)findFrameNamed:(NSString *)name;

/*!
    @property parentFrame
    @abstract The frame containing this frame, or nil if this is a top level frame.
*/
@property (nonatomic, readonly, strong) WebFrame *parentFrame;

/*!
    @property childFrames
    @abstract An array of WebFrame.
    @discussion The frames in the array are associated with a frame set or iframe.
*/
@property (nonatomic, readonly, copy) NSArray *childFrames;

/*!
    @property windowObject
    @abstract The WebScriptObject representing the frame's JavaScript window object.
*/
@property (nonatomic, readonly, strong) WebScriptObject *windowObject;

/*!
    @property globalContext
    @abstract The frame's global JavaScript execution context.
    @discussion Use this method to bridge between the WebKit and JavaScriptCore APIs.
*/
@property (nonatomic, readonly) JSGlobalContextRef globalContext;

#if JSC_OBJC_API_ENABLED
/*!
    @property javaScriptContext
    @abstract The frame's global JavaScript execution context.
    @discussion Use this method to bridge between the WebKit and Objective-C JavaScriptCore API.
*/
@property (nonatomic, readonly, strong) JSContext *javaScriptContext;
#endif // JSC_OBJC_API_ENABLED

@end


text:
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

#if NETFX_CORE
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
#else
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
#endif

#if NOSDK
using KinectEx.KinectSDK;
#elif NETFX_CORE
using WindowsPreview.Kinect;
#else
using Microsoft.Kinect;
#endif

namespace KinectEx.DVR
{
    /// <summary>
    /// A recordable / replayable version of an <c>InfraredFrame</c>.
    /// </summary>
    public class ReplayInfraredFrame : ReplayFrame
    {
        private static byte[] _staticBytes = null;
        private static ushort[] _staticData = null;

        private ushort[] _frameData = null;

        internal Stream Stream;
        internal long StreamPosition;

        /// <summary>
        /// The width (in pixels) of the infrared frame.
        /// </summary>
        public int Width { get; set; }

        /// <summary>
        /// The height (in pixels) of the infrared frame.
        /// </summary>
        public int Height { get; set; }

        /// <summary>
        /// The number of bytes per pixel
        /// </summary>
        public uint BytesPerPixel { get; private set; }

        /// <summary>
        /// The raw infrared data stored in this frame.
        /// </summary>
        public ushort[] FrameData
        {
            get
            {
                if (_frameData == null)
                {
                    // Assume we must read it from disk
                    return GetFrameDataAsync().Result;
                }
                return _frameData;
            }
        }

        // Multiple Constructor options

        /// <summary>
        /// Initializes a new instance of the <see cref="ReplayInfraredFrame"/> class.
        /// </summary>
        internal ReplayInfraredFrame() { }

#if !NOSDK
        /// <summary>
        /// Initializes a new instance of the <see cref="ReplayInfraredFrame"/> class
        /// from an <c>InfraredFrame</c>.
        /// </summary>
        /// <param name="frame">The frame.</param>
        internal ReplayInfraredFrame(InfraredFrame frame)
        {
            this.FrameType = FrameTypes.Infrared;
            this.RelativeTime = frame.RelativeTime;

            this.Width = frame.FrameDescription.Width;
            this.Height = frame.FrameDescription.Height;
            this.BytesPerPixel = frame.FrameDescription.BytesPerPixel;

            _frameData = new ushort[this.Width * this.Height];

            frame.CopyFrameDataToArray(_frameData);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ReplayInfraredFrame"/> class
        /// from an <c>InfraredFrame</c> with the data already extracted.
        /// </summary>
        /// <param name="frame">The frame.</param>
        /// <param name="frameData">The frame data.</param>
        internal ReplayInfraredFrame(InfraredFrame frame, ushort[] frameData)
        {
            this.FrameType = FrameTypes.Infrared;
            this.RelativeTime = frame.RelativeTime;

            this.Width = frame.FrameDescription.Width;
            this.Height = frame.FrameDescription.Height;
            this.BytesPerPixel = frame.FrameDescription.BytesPerPixel;

            _frameData = frameData;
        }
#endif

        /// <summary>
        /// Initializes a new instance of the <see cref="ReplayInfraredFrame"/> class
        /// from a <c>BinaryReader</c>.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns></returns>
        /// <exception cref="System.IO.IOException">The recording appears to be corrupt.</exception>
        internal static ReplayInfraredFrame FromReader(BinaryReader reader)
        {
            var frame = new ReplayInfraredFrame();

            frame.FrameType = FrameTypes.Infrared;
            frame.RelativeTime = TimeSpan.FromMilliseconds(reader.ReadDouble());
            frame.FrameSize = reader.ReadInt64();

            long frameStartPos = reader.BaseStream.Position;

            frame.Width = reader.ReadInt32();
            frame.Height = reader.ReadInt32();
            frame.BytesPerPixel = reader.ReadUInt32();

            frame.Stream = reader.BaseStream;
            frame.StreamPosition = frame.Stream.Position;

            frame.Stream.Position += frame.Width * frame.Height * frame.BytesPerPixel;

            // Do Frame Integrity Check
            if (reader.ReadString() != ReplayFrame.EndOfFrameMarker)
            {
                System.Diagnostics.Debug.WriteLine("BAD FRAME...RESETTING");
                reader.BaseStream.Position = frameStartPos + frame.FrameSize;
                if (reader.ReadString() != ReplayFrame.EndOfFrameMarker)
                {
                    throw new IOException("The recording appears to be corrupt.");
                }
                return null;
            }

            return frame;
        }

        /// <summary>
        /// Used during replay to retrieve the raw infrared data stored on
        /// disk for this frame.
        /// </summary>
        public Task<ushort[]> GetFrameDataAsync()
        {
            return Task<ushort[]>.Run(() => {
                Monitor.Enter(Stream);
                var reader = new BinaryReader(Stream);
                if (_staticBytes == null)
                    _staticBytes = new byte[this.Width * this.Height * 2];
                if (_staticData == null)
                    _staticData = new ushort[this.Width * this.Height];

                long savedPosition = Stream.Position;
                Stream.Position = StreamPosition;

                reader.Read(_staticBytes, 0, _staticBytes.Length);
                System.Buffer.BlockCopy(_staticBytes, 0, _staticData, 0, _staticBytes.Length);

                Stream.Position = savedPosition;
                Monitor.Exit(Stream);
                return _staticData;
            });
        }
    }
}


text:
import * as express from 'express';
import * as apicache from 'apicache';

import Avatars from '@dicebear/avatars-legacy';

import maleSpriteSet from '@dicebear/avatars-legacy/lib/spriteSets/male';
import femaleSpriteSet from '@dicebear/avatars-legacy/lib/spriteSets/female';

import serverConfig from '../../server.config';

const ms = require('ms');
const spriteSets: { [index: string]: Avatars } = {
  male: new Avatars(maleSpriteSet),
  female: new Avatars(femaleSpriteSet)
};

const cache = apicache.middleware;
const router = express.Router();

router.get(/\/v1\/([^/]+)\/([^/]*)\/(\d+)\.png/, cache(ms(serverConfig.v1.memoryCaching)), function(req, res, next) {
  let spriteSet = req.params[0];
  let seed = req.params[1];
  let size = req.params[2];

  if (parseInt(size) < serverConfig.v1.minSize) {
    res.status(400).send('Minimum size of ' + serverConfig.v1.minSize + 'px.');
    next();

    return;
  }

  if (parseInt(size) > serverConfig.v1.maxSize) {
    res.status(400).send('Maximum size of ' + serverConfig.v1.maxSize + 'px.');
    next();

    return;
  }

  if (undefined === spriteSets[spriteSet]) {
    res.status(400).send('Invalid sprite collection. Available: ' + Object.keys(spriteSets).join(', '));
    next();

    return;
  }

  spriteSets[spriteSet].create(seed, { size: parseInt(size) }, (err, canvas) => {
    if (err) {
      next(err);

      return;
    }

    // @ts-ignore
    let buffer = canvas.toBuffer(undefined, 9);

    res.status(200);
    res.setHeader('Content-Type', 'image/png');
    res.setHeader('Cache-Control', 'public, max-age=' + ms(serverConfig.v1.httpCaching) / 1000);
    res.end(buffer);
  });
});

export default router;


text:
package factoriesClassTests;

import static org.junit.Assert.*;
import org.junit.Test;
import decks.ObjectDeck;
import factories.ObjectDeckFactory;

/**
 * Tests for ObjectDeckFactory class
 *
 * @author Andrea Sessa
 * @author Giorgio Pea
 * @see Deck
 * @see ObjectDeck
 */
public class ObjectDeckFactoryTest {
	// A deck of object cards
	private ObjectDeck deck = (ObjectDeck) new ObjectDeckFactory().makeDeck();

	/**
	 * Test for the make method
	 */
	@Test
	public void sizeTest() {
		/*
		 * Testing if the method produces a deck with the right number of cards
		 * and a discard deck with the right number of cards
		 */
		assertEquals(12, deck.getContent().size());
		assertEquals(0, deck.getDiscardDeck().getCards().size());
	}

}


text:
APP_DIR = File.expand_path("../../..", __FILE__)
USER = ""
GROUP = ""

#worker_processes 2
worker_processes 8
working_directory APP_DIR
# user USER, GROUP

listen 3000, :tcp_nopush => true
#listen "/var/run/unicorn.sock"
pid "#{APP_DIR}/tmp/pids/unicorn.pid"

timeout 60
preload_app true

stdout_path "#{APP_DIR}/log/unicorn_stdout.log"
stderr_path "#{APP_DIR}/log/unicorn_stderr.log"

GC.respond_to?(:copy_on_write_friendly=) and GC.copy_on_write_friendly = true

before_fork do |server, worker|
  defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect!

  old_pid = "#{server.config[:pid]}.oldbin"
  if old_pid != server.pid
    begin
      sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
      Process.kill(sig, File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
    end
  end

  sleep 1
end

after_fork do |server, worker|
  defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection

  #child_pid = server.config[:pid].sub('.pid', ".#{worker.nr}.pid")
  #system("echo #{Process.pid} > #{child_pid}") # リダイレクトしてファイルに書き込む
end


text:
Ext.define('Fiddle.reportgrid.ReportGrid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.reportgrid',
    loadMask: true,
    controller: 'reportgrid',
    requires: [
        'Ext.grid.filters.Filters'
    ],
    layout: {
        type: 'card',
        deferredRender: true,
        duration: 500
    },
    mixins: [
        'Fiddle.mixin.CSVExport'
    ],
    constructor: function(config) {
        config.columns = reportManager.columns(config.reportId);
        config.plugins = [{
            ptype: 'gridfilters'
        }];
        this.callParent([config]);
    }
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>ModuleComponentSelector (Gradle API 2.3)</title>
    <meta name="date" content="2015-02-16">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="../../../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
    <link href="../../../../../groovy.ico" type="image/x-icon" rel="icon">
    <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field
Method

 | Detail:

            Field
Method

Package: org.gradle.api.artifacts.component

[Java] Interface ModuleComponentSelector

org.gradle.api.artifacts.component.ComponentSelector

All Superinterfaces:

ComponentSelector

 Criteria for selecting a component instance that is available as a module version.

Since:

1.10

Methods Summary

Methods

                            Type
                            Name and description

                            String
                            getGroup()
The group of the module to select the component from.

                            String
                            getModule()
The name of the module to select the component from.

                            String
                            getVersion()
The version of the module to select the component from.

Inherited Methods Summary

Inherited Methods

                            Methods inherited from class
                            Name

                            interface ComponentSelector
                            getDisplayName, matchesStrictly

Method Detail

public String getGroup()

 The group of the module to select the component from.

Returns:

Module group

Since:

1.10

public String getModule()

 The name of the module to select the component from.

Returns:

Module name

public String getVersion()

 The version of the module to select the component from.

Returns:

Module version

Overview

Package

Class

Deprecated

Index

Help

Frames

No Frames

Summary:

            Nested   Field
Method

 | Detail:

            Field
Method

Gradle API 2.3


text:
/* @ignore:start */
omit this from scan
/* @ignore:end */

123456

function test() {
    console.log("ABC");
}


text:
#import "EC2GetPasswordDataRequest.h"

@implementation EC2GetPasswordDataRequest

@synthesize instanceId;

-(id)init
{
    if (self = [super init]) {
        instanceId = nil;
    }

    return self;
}

-(id)initWithInstanceId:(NSString *)theInstanceId
{
    if (self = [self init]) {
        self.instanceId = theInstanceId;
    }

    return self;
}

-(NSString *)description
{
    NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256];

    [buffer appendString:@"{"];
    [buffer appendString:[[[NSString alloc] initWithFormat:@"InstanceId: %@,", instanceId] autorelease]];
    [buffer appendString:[super description]];
    [buffer appendString:@"}"];

    return [buffer autorelease];
}

-(void)dealloc
{
    [instanceId release];

    [super dealloc];
}

@end


text:
require 'spec_helper'

describe LongTweet::IdealSplitter do
  subject { LongTweet::IdealSplitter.new words }
  let(:lorem) { %w{lorenm ipsummm dolor sit ament} }
  let(:words) { (lorem*8).join(' ') }
  let(:first_tweet) { subject.split.first }

  it 'only have full words in tweets' do
    last_word = first_tweet.text.split.last
    expect(lorem.include? last_word).to be_true
  end

  it 'doesnt exceed 140 characters when creating a tweet' do
    splitter = LongTweet::IdealSplitter.new('a '*140)
    text = splitter.split.first.text
    expect(text.length < 141).to be_true
  end

  it 'returns a tweet when there are < 140 characeters' do
    result = LongTweet::IdealSplitter.new('derp').split
    expect(result.first.text).to eq('derp')
  end

  it 'returns a postable object' do
    expect(first_tweet).to respond_to :post
  end
end


text:
package org.springframework.cloud.netflix.ribbon;

import com.netflix.loadbalancer.Server;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author Rico Pahlisch
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DefaultServerIntrospectorDefaultTests.TestConfiguration.class)
public class DefaultServerIntrospectorDefaultTests {

	@Autowired
	private ServerIntrospector serverIntrospector;

	@Test
	public void testDefaultSslPorts() {
		Server serverMock = mock(Server.class);
		when(serverMock.getPort()).thenReturn(443);
		assertThat(serverIntrospector.isSecure(serverMock)).isTrue();
		when(serverMock.getPort()).thenReturn(8443);
		assertThat(serverIntrospector.isSecure(serverMock)).isTrue();

		when(serverMock.getPort()).thenReturn(16443);
		assertThat(serverIntrospector.isSecure(serverMock)).isFalse();
	}

	@Configuration
	@EnableConfigurationProperties(ServerIntrospectorProperties.class)
	protected static class TestConfiguration {

		@Bean
		public DefaultServerIntrospector defaultServerIntrospector() {
			return new DefaultServerIntrospector();
		}

	}

}


text:
require 'spec_helper'

describe NewProjectJob do
  before do
    @project = FactoryGirl.create(:project)
  end

  describe "#perform" do
    before do
      NewProjectJob.perform(@project.id)
    end

    it "should generate an object key" do
      WebMock.should have_requested(:post, "http://localhost:7979/object")
    end
  end
end


text:
"""todolist URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]


text:
__author__ = 'eveR'

from rest_framework import authentication, permissions, filters

# to available when were permissions

class DefaultViewSetMixin(object):
    # authentication_classes= (
    #     authentication.BaseAuthentication,
    #     authentication.TokenAuthentication,
    # )
    # permissions_classes = (
    #     permissions.IsAuthenticated,
    # )
    filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter, )
    paginate_by = 50
    paginate_by_param = 'page_size'
    max_paginate_by = 100


text:
package alimt

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// GetTitleIntelligence invokes the alimt.GetTitleIntelligence API synchronously
func (client *Client) GetTitleIntelligence(request *GetTitleIntelligenceRequest) (response *GetTitleIntelligenceResponse, err error) {
	response = CreateGetTitleIntelligenceResponse()
	err = client.DoAction(request, response)
	return
}

// GetTitleIntelligenceWithChan invokes the alimt.GetTitleIntelligence API asynchronously
func (client *Client) GetTitleIntelligenceWithChan(request *GetTitleIntelligenceRequest) (<-chan *GetTitleIntelligenceResponse, <-chan error) {
	responseChan := make(chan *GetTitleIntelligenceResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.GetTitleIntelligence(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// GetTitleIntelligenceWithCallback invokes the alimt.GetTitleIntelligence API asynchronously
func (client *Client) GetTitleIntelligenceWithCallback(request *GetTitleIntelligenceRequest, callback func(response *GetTitleIntelligenceResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *GetTitleIntelligenceResponse
		var err error
		defer close(result)
		response, err = client.GetTitleIntelligence(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// GetTitleIntelligenceRequest is the request struct for api GetTitleIntelligence
type GetTitleIntelligenceRequest struct {
	*requests.RpcRequest
	CatLevelThreeId requests.Integer `position:"Body" name:"CatLevelThreeId"`
	CatLevelTwoId   requests.Integer `position:"Body" name:"CatLevelTwoId"`
	Keywords        string           `position:"Body" name:"Keywords"`
	Platform        string           `position:"Body" name:"Platform"`
	Extra           string           `position:"Body" name:"Extra"`
}

// GetTitleIntelligenceResponse is the response struct for api GetTitleIntelligence
type GetTitleIntelligenceResponse struct {
	*responses.BaseResponse
	Code      int    `json:"Code" xml:"Code"`
	Message   string `json:"Message" xml:"Message"`
	RequestId string `json:"RequestId" xml:"RequestId"`
	Data      Data   `json:"Data" xml:"Data"`
}

// CreateGetTitleIntelligenceRequest creates a request to invoke GetTitleIntelligence API
func CreateGetTitleIntelligenceRequest() (request *GetTitleIntelligenceRequest) {
	request = &GetTitleIntelligenceRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("alimt", "2018-10-12", "GetTitleIntelligence", "", "")
	request.Method = requests.POST
	return
}

// CreateGetTitleIntelligenceResponse creates a response to parse from GetTitleIntelligence response
func CreateGetTitleIntelligenceResponse() (response *GetTitleIntelligenceResponse) {
	response = &GetTitleIntelligenceResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
define([
    'helpers/SpawnHelper',
    'mustache!house',
    'mustache!mortgageMarketView'
], function(
    SpawnHelper,
    houseTemplate,
    mmvTemplate
){
    'use strict';

    return Backbone.View.extend({

        initialize: function(){
            this.spawnHelper = new SpawnHelper();
            this.listenTo(this.spawnHelper, 'spawnMortgage', _(this.showHouse).bind(this));
        },

        render: function(){
            this.$el.append(mmvTemplate());
            this.$el.on('click', '.house', _(this.houseClicked).bind(this));
        },

        showHouse: function(houseType){
            var self = this;
            var v = this.$('.view-main');
            var left = (Math.random() * 80);
            var top = (Math.random() * 100);

            var house = houseTemplate({type: houseType, left: left, top: top});

            window.setTimeout(function() {
                self.removeHouse(house);
            }, 3000);

            v.append(house);
            house.animate({opacity: 1}, 500);
        },

        houseClicked: function(event){
            var house = $(event.target).closest('.house');

            this.trigger('boughtMortgage', house);
            house.remove();
        },

        removeHouse: function(house) {
            var boundHouseRemove = _(house.remove).bind(house);

            house.animate({opacity: 0}, 500, function(){
                boundHouseRemove();
            });
        }

    });
});


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;

namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
    public abstract partial class AbstractUserDiagnosticTest
    {
        private class FixAllDiagnosticProvider : FixAllContext.DiagnosticProvider
        {
            private readonly TestDiagnosticAnalyzerDriver _testDriver;
            private readonly ImmutableHashSet<string> _diagnosticIds;

            public FixAllDiagnosticProvider(TestDiagnosticAnalyzerDriver testDriver, ImmutableHashSet<string> diagnosticIds)
            {
                _testDriver = testDriver;
                _diagnosticIds = diagnosticIds;
            }

            public override async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
            {
                var root = await document.GetSyntaxRootAsync(cancellationToken);
                var diags = await _testDriver.GetDocumentDiagnosticsAsync(document, root.FullSpan);
                diags = diags.Where(diag => _diagnosticIds.Contains(diag.Id));
                return diags;
            }

            public override Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken)
                => GetProjectDiagnosticsAsync(project, true);

            public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken)
                => GetProjectDiagnosticsAsync(project, false);

            private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(
                Project project, bool includeAllDocumentDiagnostics)
            {
                var diags = includeAllDocumentDiagnostics
                    ? await _testDriver.GetAllDiagnosticsAsync(project)
                    : await _testDriver.GetProjectDiagnosticsAsync(project);
                diags = diags.Where(diag => _diagnosticIds.Contains(diag.Id));
                return diags;
            }
        }
    }
}


text:
import Expo, { Font, Contacts, Permissions } from 'expo';
import React, { Component } from 'react';
import { StyleSheet, Text, View, ListView, TouchableOpacity, Modal, Image } from 'react-native';
import { Button } from 'react-native-elements';

import ContactList from './components/contact_list';

export default class App extends Component {
  constructor(props){
    super(props)
    this.handlePress = this.handlePress.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.handleClose = this.handleClose.bind(this)
    this.getContacts = this.getContacts.bind(this)
    this.requestContactPerm = this.requestContactPerm.bind(this)
    this.formatContacts = this.formatContacts.bind(this)

    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

    this.state = {
      fontLoaded: false,
      contactsVis: false,
      contactPerm : null,
      contactsFull: null,
      contactsData: null,
      searchitem: null,
      ds: ds,
    }
  }

  async requestContactPerm(){
    const permission = await Permissions.askAsync(Permissions.CONTACTS);
    this.setState({contactPerm: permission.status})
    this.getContacts()
  }

  async getContacts(){
    const contactsFull = await Contacts.getContactsAsync({
      fields: [ Contacts.PHONE_NUMBERS ],
      pageSize: 10000,
    });
    const contacts = contactsFull.data.filter((contact) => {
      return contact.phoneNumbers.length > 0;
    })
    const formattedContacts = this.formatContacts(contacts)
    this.setState({
      contactsFull: formattedContacts,
      contactsData: this.state.ds.cloneWithRows(formattedContacts)
    })
  }

  formatContacts(contacts){
    return contacts.map((contact) => {
      for (var i = 0; i < contact.phoneNumbers.length; i++) {
        const label = contact.phoneNumbers[i].label ? contact.phoneNumbers[i].label : 'mobile';
        const number = contact.phoneNumbers[i].number.replace(/[^0-9]*/g, '').toString();
        return {
          name: contact.firstName.toLowerCase() + ' ' + contact.lastName.toLowerCase(),
          subtitle: label,
          phone: number,
        }
      }
    })
  }

  handlePress(){
    if (this.state.contactPerm !== 'granted') {
      alert("We're not the NSA! We need permission to access your contacts. Namaste!")
      this.requestContactPerm()
    } else {
      this.setState({contactsVis: true})
    }
  }

  handleSearch(name){
    const contacts = this.state.contactsFull.filter((contact) => {
      return (contact.name.indexOf(name.toLowerCase()) !== -1)
    })
    this.setState({
      searchitem: name,
      contactsData: this.state.ds.cloneWithRows(contacts)
    })
  }

  handleClose(){
    this.setState({
      contactsVis: false,
      searchitem: null,
    })
  }

  componentWillMount(){
    if (this.state.contactPerm !== 'granted') this.requestContactPerm()
    else if (this.state.contactsData === null) this.getContacts()
  }

  async componentDidMount(){
    await Font.loadAsync({
      'Prisma': require('./assets/fonts/Prisma.ttf'),
    });
    this.setState({ fontLoaded: true });
  }

  render(){
    return (
      <Image source={require('./assets/images/budda.png')} style={styles.bgImage} >
        <Modal animationType={"slide"} transparent={false} visible={this.state.contactsVis} >
          <ContactList contacts={this.state.contactsData}
                        handleSearch={this.handleSearch}
                        handleClose={this.handleClose}
                        />
        </Modal>

        { this.state.fontLoaded ?
          <Button raised
                  title="Send a Namaste"
                  onPress={this.handlePress}
                  fontSize={30}
                  fontFamily="Prisma"
                  backgroundColor="rgba(255, 255, 255, 0.8)"
                  color="#000"
                  containerViewStyle={styles.button}
                  />
          : null
        }
      </Image>
    );
  }
}

const styles = StyleSheet.create({
  bgImage: {
    flex: 1,
    width: null,
    height: null,
    backgroundColor: '#FFF8C6',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  button: {
    bottom: 75,
    borderColor: '#000',
    borderWidth: 5,
    borderRadius: 2,
  }
});

Expo.registerRootComponent(App);


text:
using Mediachase.Commerce;
using System;

namespace EPiServer.Reference.Commerce.Site.Features.Cart.ViewModels
{
    public class ShippingMethodViewModel
    {
        public Guid Id { get; set; }
        public string DisplayName { get; set; }
        public Money Price { get; set; }
    }
}


text:
date: 2017-01-17T16:58:30+02:00
prev: /magento-connector-setup-and-configuration/time-setting
next: /magento-connector-setup-and-configuration/sync-scheduler
title: Sync Configuration
toc: true
aliases :
  - /magento-connector-setup-and-configuration/sync-configuration
icon: "3.4"
weight: 304
---

## 3.4 Sync Configuration

{{% notice goto %}}
Navigation: Acumatica > Configuration > Acumatica > Sync Configuration
{{% /notice %}}

![sync-configuration](images/sync-configuration.png?classes=shadow)

### 3.4.1	Warehouse Details

On warehouse details screen(as shown below) user can select the "Default Warehouse" and fetch the updated warehouse details from Acumatica
by clicking on "Update Warehouse Data" and after selecting the warehouse click on Save Config button.

![warehouse-details](images/warehouse-details.png?classes=shadow)

### 3.4.2	Attribute Sync

* Enable Product and Customer sync option in Attribute Sync list to display and enable Product Attribute Sync and Customer Attribute Sync on the Manual Sync page
* Click "Save Config" to save the changes made to configuration

![attribute-sync](images/attribute-sync.png?classes=shadow)

{{% notice goto %}}
Navigation: Magento Admin Panel > Acumatica > Manual Sync
{{% /notice %}}

![manual-sync](images/manual-sync.png?classes=shadow)

#### Action

 When user clicks on "Sync now" button, manual sync of that particular entity will execute
When user clicks on "Sync Status" it will redirect to Sync Logs page and by default it will show the entity for which "Sync Status" is clicked.

![sync-status](images/sync-status.png?classes=shadow)

### 3.4.3	Category Sync

*	Enable Category Sync to display it on Manual sync page and Enable Individual Sync to display it on every Category page.
*	Click save Config to save the changes made to configuration

![category-sync](images/category-sync.png?classes=shadow)

{{% notice goto %}}
Navigation: Magento Admin Panel > Acumatica > Manual Sync
{{% /notice %}}

![category-sync-1](images/category-sync-1.png?classes=shadow)

#### Individual sync

 Navigate to category details page and click on the "Sync Now" button as shown below

![category-sync-2](images/category-sync-2.png?classes=shadow)

#### Sync Direction

Sync direction for each entity can be configured as follows.
Refer > **SYNC DIRECTIONS** section for more details on the direction type

![category-sync-3](images/category-sync-3.png?classes=shadow)

 By default Auto Cron will be 'NO'. If, Auto Cron is set to 'Yes' then, Category will sync automatically based on the setting. Click Save Config to save the changes made.

![category-sync-4](images/category-sync-4.png?classes=shadow)

### 3.4.4	Product Sync

*	Enable Product Sync to display it on Manual Sync page
*	By default, Individual Sync and Auto Cron are disabled
*	If Indexing after sync is set to 'yes', indexing job will be performed after the Product sync is completed.
*	Click on Save Config to save changes made to configuration

![product-sync](images/product-sync.png?classes=shadow)

After saving the configuration, Navigate to Manual sync page

![product-sync-1](images/product-sync-1.png?classes=shadow)

#### Individual Sync

 Navigate to product details page and click on the "Sync Now" button as shown below

![product-sync-2](images/product-sync-2.png?classes=shadow)

### 3.4.5	Product Inventory and Price Sync

*	Enable Inventory and Price Sync to display it on Manual Sync page
*	By default Auto Cron will be set to 'No'

![product-sync-3](images/product-sync-3.png?classes=shadow)

![product-sync-4](images/product-sync-4.png?classes=shadow)

Below are the options for Sync:

*	Inventory only: Only Inventory would be synced
*	Price only: Only Price would be synced
*	Inventory and Price: Both Inventory and Price would be synced

![product-sync-5](images/product-sync-5.png?classes=shadow)

### 3.4.6	Product Image Sync

*	Enable Image Sync to display it on Manual Sync page
*	Web service Name should be same as the Service ID configured in Acumatica. Refer the below path.
"System > Integration > Web services"

![product-sync-6](images/product-sync-6.png?classes=shadow)

After saving the configuration, Navigate to Manual sync page

![product-sync-7](images/product-sync-7.png?classes=shadow)

### 3.4.7	Product Configurator Sync

*	Enable Product Configurator Sync as shown below, to display it on Manual Sync page

![product-sync-8](images/product-sync-8.png?classes=shadow)

![product-sync-9](images/product-sync-9.png?classes=shadow)

### 3.4.8	Customer Sync

{{% notice goto %}}
Navigation: Magento Admin Panel > Acumatica > Configuration > Acumatica > Sync Configuration
{{% /notice %}}

*	Enable Customer Sync to display it on Manual Sync page and enable Individual Sync to display it on Customer detail page.
*	By default, Individual Sync and Auto Cron are disabled
*	Click Save Config to save changes made to configuration
*	Default Customer Class: Values will be fetched from Acumatica and user can also click on "update Customer Class Data" to fetch the latest data from Acumatica.
*	Default Customer Terms: Values will be fetched from Acumatica and user can also click on "update Customer Terms Data" to fetch the latest data from Acumatica.
*	Default Customer Statement Cycle: Values will be fetched from Acumatica and user can click on "update Customer Statement Cycle Data" to fetch the latest data from Acumatica.

![customer-sync](images/customer-sync.png?classes=shadow)

After saving the configuration, Navigate to Manual sync page

![customer-sync](images/customer-sync-1.png?classes=shadow)

#### Individual Sync

 Navigate to customer details page and click on the "Sync Now" button as shown below

![customer-sync](images/customer-sync-2.png?classes=shadow)

### 3.4.9	Order Sync

*	Enable Order Sync to display it on Manual Sync page and enable Individual Sync to display it on Order detail page
*	By default Individual Sync and Auto Cron will be disabled
*	Order Type: Mention the Order Type to be considered for Sync
*	Real Time Sync: If enabled, after successfully placing an order, sync will execute and create an order in Acumatica. If Real time sync is not enabled, system will wait for the cron to execute the sync or admin can use individual sync option to sync specific order.
*	Default Sales Account: The data will be fetched from Acumatica Instance and user can also click on "update Sales Account Data" to fetch the latest data from Acumatica.
*	Default Payment Method: Select the default payment method from the dropdown list.  To update the payment method data click on "Update Payment Method Data"
*	Cash Account: Add the cash account number as configured in Acumatica
*	Retry Failed Orders: When Retry Failed Orders is set to 'Yes', Order Sync considers the failed orders for the number of times it is configured. By default number of Retries value is set to '3' For e.g. If Order '123456' is failed to sync to Acumatica, and the number of retries value is set to '4' then during Order sync, system will consider this order for sync for 4 times and the 5th time system will skip this order to sync if the order still fails to sync.
* Order Statuses: Select the Order status to sync the Orders with those statuses to Acumatica

![order-sync](images/order-sync.png?classes=shadow)

![order-sync-1](images/order-sync-1.png?classes=shadow)

#### Individual Sync

 Navigate to order details page and click on the "Sync Now" button as shown below

![order-sync-2](images/order-sync-2.png?classes=shadow)

### 3.4.10	Failed Order Sync

{{% notice goto %}}
Navigation: Magento Admin Panel > Acumatica > Configuration > Acumatica > Sync Configuration
{{% /notice %}}

*	Enable Failed Order Sync to display it on Manual Sync screen.
*	By default Auto Cron will be disabled
*	Set Number of days  and Connector will consider the failed orders only from the current date to last 'x' days duration to sync

![order-sync-3](images/order-sync-3.png?classes=shadow)

![order-sync-4](images/order-sync-4.png?classes=shadow)


text:
<?php
/**
 * Horde Log package
 *
 * This package is based on Zend_Log from the Zend Framework
 * (http://framework.zend.com).  Both that package and this
 * one were written by Mike Naberezny and Chuck Hagenbuch.
 *
 * @category Horde
 * @package  Horde_Log
 * @subpackage Formatters
 * @author   Mike Naberezny <mike@maintainable.com>
 * @author   Chuck Hagenbuch <chuck@horde.org>
 * @license  http://opensource.org/licenses/bsd-license.php BSD
 */

/**
 * @category Horde
 * @package  Horde_Log
 * @subpackage Formatters
 * @author   Mike Naberezny <mike@maintainable.com>
 * @author   Chuck Hagenbuch <chuck@horde.org>
 * @license  http://opensource.org/licenses/bsd-license.php BSD
 */
class Horde_Log_Formatter_Simple
{
    /**
     * Format string
     *
     * @var string
     */
    protected $_format;

    /**
     * Constructor
     */
    public function __construct($options = null)
    {
        if (is_array($options) && isset($options['format'])) {
            $format = $options['format'];
        } else {
            $format = $options;
        }

        if (is_null($format)) {
            $format = '%timestamp% %levelName%: %message%' . PHP_EOL;
        }

        if (!is_string($format)) {
            throw new Horde_Log_Exception('Format must be a string');
        }

        $this->_format = $format;
    }

    /**
     * Formats an event to be written by the handler.
     *
     * @param  array    $event    Log event
     * @return string             formatted line
     */
    public function format($event)
    {
        $output = $this->_format;
        foreach ($event as $name => $value) {
            $output = str_replace("%$name%", $value, $output);
        }
        return $output;
    }

}


text:
function varargout = spm_slice_vol(varargin)
% returns a slice through a memory mapped image - a compiled routine
% FORMAT X = spm_slice_vol(V,A,dim,hold);
% V      -  is a memory mapped image volume
% A      -  is a 4 x 4 transformation matrix
% dim    -  [i j] defines the two dimensions of the output image. The
%           coordinates in 3-D space of the voxels in this image are assumed
%           to range from 1,1,0 to i,j,0.
% hold   -  sets the interpolation method for the resampling.
%           0          Zero-order hold (nearest neighbour).
%           1          First-order hold (trilinear interpolation).
%           2->127     Higher order Lagrange (polynomial) interpolation using
%                      different holds (second-order upwards).
%          -127 - -1   Different orders of sinc interpolation.
% X      -  output image
%_______________________________________________________________________
%
% spm_slice_vol returns a section through a memory mapped image volume
% on disk.  This section is the transverse slice at z = 0 after linear
% transformation according to matrix A
%
% see also spm_sample_vol.m
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% John Ashburner
% $Id: spm_slice_vol.m 1143 2008-02-07 19:33:33Z spm $

%-This is merely the help file for the compiled routine
error('spm_slice_vol.c not compiled - see Makefile')


text:
/**
 * This package contains classes created from automatically generated
 * sources. The tool used to generate these sources was JNAerator.
 */

package com.cathive.sass.jna;


text:
package org.mp4parser.ismvserver;

import org.mp4parser.IsoFile;
import org.mp4parser.boxes.microsoft.PiffTrackEncryptionBox;
import org.mp4parser.tools.Path;

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

/**
 * Created by sannies on 18.01.2016.
 */
public class ExtractKeyId {
    public static void main(String[] args) throws IOException {
        IsoFile isoFile = new IsoFile(args[0]);
        List<PiffTrackEncryptionBox> piffTencs =  Path.getPaths(isoFile, "moov/trak/mdia/minf/stbl/stsd/enca/sinf/schi/uuid");
        for (PiffTrackEncryptionBox piffTenc : piffTencs) {
            System.err.println(piffTenc.getDefault_KID());
        }
    }
}


text:
package me.dinosparkour.audio;

import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.VoiceChannel;

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

public class TrackManager extends AudioEventAdapter {

    private final AudioPlayer player;
    private final Queue<AudioInfo> queue;

    public TrackManager(AudioPlayer player) {
        this.player = player;
        this.queue = new LinkedBlockingQueue<>();
    }

    public void queue(AudioTrack track, Member author) {
        AudioInfo info = new AudioInfo(track, author);
        queue.add(info);

        if (player.getPlayingTrack() == null) {
            player.playTrack(track);
        }
    }

    @Override
    public void onTrackStart(AudioPlayer player, AudioTrack track) {
        AudioInfo info = queue.element();
        VoiceChannel vChan = info.getAuthor().getVoiceState().getChannel();
        if (vChan == null) { // User has left all voice channels
            player.stopTrack();
        } else {
            info.getAuthor().getGuild().getAudioManager().openAudioConnection(vChan);
        }
    }

    @Override
    public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
        Guild g = queue.poll().getAuthor().getGuild();
        if (queue.isEmpty()) {
            g.getAudioManager().closeAudioConnection();
        } else {
            player.playTrack(queue.element().getTrack());
        }
    }

    public void shuffleQueue() {
        List<AudioInfo> tQueue = new ArrayList<>(getQueuedTracks());
        AudioInfo current = tQueue.get(0);
        tQueue.remove(0);
        Collections.shuffle(tQueue);
        tQueue.add(0, current);
        purgeQueue();
        queue.addAll(tQueue);
    }

    public Set<AudioInfo> getQueuedTracks() {
        return new LinkedHashSet<>(queue);
    }

    public void purgeQueue() {
        queue.clear();
    }

    public void remove(AudioInfo entry) {
        queue.remove(entry);
    }

    public AudioInfo getTrackInfo(AudioTrack track) {
        return queue.stream().filter(audioInfo -> audioInfo.getTrack().equals(track)).findFirst().orElse(null);
    }
}


text:
package org.geoint.lbac.impl.policy.restriction;

import org.geoint.lbac.impl.command.MarkingChangeCommand;
import org.geoint.lbac.marking.SecurityMarking;

/**
 * A SecurityRestriction is defined by a security policy and is applied against
 * the context of a {@link SecurityMarking} instance.
 *
 * A SecurityRestriction defines the restriction itself and, if the restriction
 * is triggered for an action on the {@link SecurityMarking}, a
 * {@link RestrictionStrategy} is returned to be executed to run in lue of the
 * previous operation.
 *
 */
public interface SecurityRestriction {

    /**
     * Check if this command is restricted, returning a new command(s) that
     * replaces the provided command.
     *
     * @param command
     * @return replacement command(s) if the restriction changes the command or
     * null if no changes are needed
     * @throws SecurityRestrictionException if the command cannot be made
     */
    MarkingChangeCommand[] restrict(MarkingChangeCommand command)
            throws SecurityRestrictionException;
}


text:
	#define GB_APU_OVERCLOCK 1
#endif

#if GB_APU_OVERCLOCK & (GB_APU_OVERCLOCK - 1)
	#error "GB_APU_OVERCLOCK must be a power of 2"
#endif

class Gb_Osc {
protected:

	// 11-bit frequency in NRx3 and NRx4
	int frequency() const { return (regs [4] & 7) * 0x100 + regs [3]; }

	void update_amp( blip_time_t, int new_amp );
	int write_trig( int frame_phase, int max_len, int old_data );
public:

	enum { clk_mul  = GB_APU_OVERCLOCK };
	enum { dac_bias = 7 };

	Blip_Buffer*    outputs [4];// NULL, right, left, center
	Blip_Buffer*    output;     // where to output sound
	BOOST::uint8_t* regs;       // osc's 5 registers
	int             mode;       // mode_dmg, mode_cgb, mode_agb
	int             dac_off_amp;// amplitude when DAC is off
	int             last_amp;   // current amplitude in Blip_Buffer
	typedef Blip_Synth<blip_good_quality,1> Good_Synth;
	typedef Blip_Synth<blip_med_quality ,1> Med_Synth;
	Good_Synth const* good_synth;
	Med_Synth  const* med_synth;

	int         delay;      // clocks until frequency timer expires
	int         length_ctr; // length counter
	unsigned    phase;      // waveform phase (or equivalent)
	bool        enabled;    // internal enabled flag

	void clock_length();
	void reset();
};

class Gb_Env : public Gb_Osc {
public:
	Gb_Env() : env_enabled(false), env_delay(0) {}
	int  env_delay;
	int  volume;
	bool env_enabled;

	void clock_envelope();
	bool write_register( int frame_phase, int reg, int old_data, int data );

	void reset()
	{
		env_delay = 0;
		volume    = 0;
		Gb_Osc::reset();
	}
protected:
	// Non-zero if DAC is enabled
	int dac_enabled() const { return regs [2] & 0xF8; }
private:
	void zombie_volume( int old, int data );
	int reload_env_timer();
};

class Gb_Square : public Gb_Env {
public:
	bool write_register( int frame_phase, int reg, int old_data, int data );
	void run( blip_time_t, blip_time_t );

	void reset()
	{
		Gb_Env::reset();
		delay = 0x40000000; // TODO: something less hacky (never clocked until first trigger)
	}
private:
	// Frequency timer period
	int period() const { return (2048 - frequency()) * (4 * clk_mul); }
};

class Gb_Sweep_Square : public Gb_Square {
public:
	int  sweep_freq;
	int  sweep_delay;
	bool sweep_enabled;
	bool sweep_neg;

	void clock_sweep();
	void write_register( int frame_phase, int reg, int old_data, int data );

	void reset()
	{
		sweep_freq    = 0;
		sweep_delay   = 0;
		sweep_enabled = false;
		sweep_neg     = false;
		Gb_Square::reset();
	}
private:
	enum { period_mask = 0x70 };
	enum { shift_mask  = 0x07 };

	void calc_sweep( bool update );
	void reload_sweep_timer();
};

class Gb_Noise : public Gb_Env {
public:

	int divider; // noise has more complex frequency divider setup

	void run( blip_time_t, blip_time_t );
	void write_register( int frame_phase, int reg, int old_data, int data );

	void reset()
	{
		divider = 0;
		Gb_Env::reset();
		delay = 4 * clk_mul; // TODO: remove?
	}
private:
	enum { period2_mask = 0x1FFFF };

	int period2_index() const { return regs [3] >> 4; }
	int period2( int base = 8 ) const { return base << period2_index(); }
	unsigned lfsr_mask() const { return (regs [3] & 0x08) ? ~0x4040 : ~0x4000; }
};

class Gb_Wave : public Gb_Osc {
public:
	int sample_buf; // last wave RAM byte read (hardware has this as well)

	void write_register( int frame_phase, int reg, int old_data, int data );
	void run( blip_time_t, blip_time_t );

	// Reads/writes wave RAM
	int read( unsigned addr ) const;
	void write( unsigned addr, int data );

	void reset()
	{
		sample_buf = 0;
		Gb_Osc::reset();
	}

private:
	enum { bank40_mask = 0x40 };
	enum { bank_size   = 32 };

	int agb_mask;               // 0xFF if AGB features enabled, 0 otherwise
	BOOST::uint8_t* wave_ram;   // 32 bytes (64 nybbles), stored in APU

	friend class Gb_Apu;

	// Frequency timer period
	int period() const { return (2048 - frequency()) * (2 * clk_mul); }

	// Non-zero if DAC is enabled
	int dac_enabled() const { return regs [0] & 0x80; }

	void corrupt_wave();

	BOOST::uint8_t* wave_bank() const { return &wave_ram [(~regs [0] & bank40_mask) >> 2 & agb_mask]; }

	// Wave index that would be accessed, or -1 if no access would occur
	int access( unsigned addr ) const;
};

inline int Gb_Wave::read( unsigned addr ) const
{
	int index = access( addr );
	return (index < 0 ? 0xFF : wave_bank() [index]);
}

inline void Gb_Wave::write( unsigned addr, int data )
{
	int index = access( addr );
	if ( index >= 0 )
		wave_bank() [index] = data;;
}

#endif


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import os
import re
from builtins import str

from future.utils import PY3
from pex.interpreter import PythonInterpreter

from pants.backend.python.interpreter_cache import PythonInterpreterCache
from pants.backend.python.python_requirement import PythonRequirement
from pants.backend.python.subsystems.python_setup import PythonSetup
from pants.backend.python.targets.python_requirement_library import PythonRequirementLibrary
from pants.backend.python.tasks.resolve_requirements import ResolveRequirements
from pants.base.build_environment import get_buildroot
from pants.util.contextutil import temporary_dir, temporary_file
from pants.util.process_handler import subprocess
from pants_test.task_test_base import TaskTestBase

class ResolveRequirementsTest(TaskTestBase):
  @classmethod
  def task_type(cls):
    return ResolveRequirements

  def test_resolve_simple_requirements(self):
    noreqs_tgt = self._fake_target('noreqs', [])
    ansicolors_tgt = self._fake_target('ansicolors', ['ansicolors==1.0.2'])

    # Check that the module is unavailable unless specified as a requirement (proves that
    # the requirement isn't sneaking in some other way, which would render the remainder
    # of this test moot.)
    _, stderr_data = self._exercise_module(self._resolve_requirements([noreqs_tgt]), 'colors')

    try:
      self.assertIn("ModuleNotFoundError: No module named 'colors'", stderr_data)
    except AssertionError:
      # < Python 3.6 uses ImportError instead of ModuleNotFoundError.
      # Python < 3 uses not quotes for module, python >= 3 does.
      self.assertNotEqual(re.search(r"ImportError: No module named '?colors'?", stderr_data), None)

    # Check that the module is available if specified as a requirement.
    stdout_data, stderr_data = self._exercise_module(self._resolve_requirements([ansicolors_tgt]),
                                                     'colors')
    self.assertEqual('', stderr_data.strip())

    path = stdout_data.strip()
    # Check that the requirement resolved to what we expect.
    self.assertTrue(path.endswith('/.deps/ansicolors-1.0.2-{}-none-any.whl/colors.py'.format('py3' if PY3 else 'py2')))
    # Check that the path is under the test's build root, so we know the pex was created there.
    self.assertTrue(path.startswith(os.path.realpath(get_buildroot())))

  def _fake_target(self, spec, requirement_strs):
    requirements = [PythonRequirement(r) for r in requirement_strs]
    return self.make_target(spec=spec, target_type=PythonRequirementLibrary,
                            requirements=requirements)

  def _resolve_requirements(self, target_roots, options=None):
    with temporary_dir() as cache_dir:
      options = options or {}
      python_setup_opts = options.setdefault(PythonSetup.options_scope, {})
      python_setup_opts['interpreter_cache_dir'] = cache_dir
      interpreter = PythonInterpreter.get()
      python_setup_opts['interpreter_search_paths'] = [os.path.dirname(interpreter.binary)]
      context = self.context(target_roots=target_roots, options=options,
                             for_subsystems=[PythonInterpreterCache])

      # We must get an interpreter via the cache, instead of using the value of
      # PythonInterpreter.get() directly, to ensure that the interpreter has setuptools and
      # wheel support.
      interpreter_cache = PythonInterpreterCache.global_instance()
      interpreters = interpreter_cache.setup(filters=[str(interpreter.identity.requirement)])
      context.products.get_data(PythonInterpreter, lambda: interpreters[0])

      task = self.create_task(context)
      task.execute()

      return context.products.get_data(ResolveRequirements.REQUIREMENTS_PEX)

  def _exercise_module(self, pex, expected_module):
    with temporary_file(binary_mode=False) as f:
      f.write('import {m}; print({m}.__file__)'.format(m=expected_module))
      f.close()
      proc = pex.run(args=[f.name], blocking=False,
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      stdout, stderr = proc.communicate()
      return (stdout.decode('utf-8'), stderr.decode('utf-8'))


text:
"""
.. _ex-inverse-source-power:

==========================================
Compute source power using DICS beamformer
==========================================

Compute a Dynamic Imaging of Coherent Sources (DICS) :footcite:`GrossEtAl2001`
filter from single-trial activity to estimate source power across a frequency
band. This example demonstrates how to source localize the event-related
synchronization (ERS) of beta band activity in the
:ref:`somato dataset <somato-dataset>`.
"""
# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#         Roman Goj <roman.goj@gmail.com>
#         Denis Engemann <denis.engemann@gmail.com>
#         Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD-3-Clause

# %%

import numpy as np
import mne
from mne.datasets import somato
from mne.time_frequency import csd_morlet
from mne.beamformer import make_dics, apply_dics_csd

print(__doc__)

# %%
# Reading the raw data and creating epochs:
data_path = somato.data_path()
subject = '01'
task = 'somato'
raw_fname = (data_path / f'sub-{subject}' / 'meg' /
             f'sub-{subject}_task-{task}_meg.fif')

# Use a shorter segment of raw just for speed here
raw = mne.io.read_raw_fif(raw_fname)
raw.crop(0, 120)  # one minute for speed (looks similar to using all ~800 sec)

# Read epochs
events = mne.find_events(raw)

epochs = mne.Epochs(raw, events, event_id=1, tmin=-1.5, tmax=2, preload=True)
del raw

# Paths to forward operator and FreeSurfer subject directory
fname_fwd = (data_path / 'derivatives' / f'sub-{subject}' /
             f'sub-{subject}_task-{task}-fwd.fif')

subjects_dir = data_path / 'derivatives' / 'freesurfer' / 'subjects'

# %%
# We are interested in the beta band. Define a range of frequencies, using a
# log scale, from 12 to 30 Hz.
freqs = np.logspace(np.log10(12), np.log10(30), 9)

# %%
# Computing the cross-spectral density matrix for the beta frequency band, for
# different time intervals. We use a decim value of 20 to speed up the
# computation in this example at the loss of accuracy.
csd = csd_morlet(epochs, freqs, tmin=-1, tmax=1.5, decim=20)
csd_baseline = csd_morlet(epochs, freqs, tmin=-1, tmax=0, decim=20)
# ERS activity starts at 0.5 seconds after stimulus onset
csd_ers = csd_morlet(epochs, freqs, tmin=0.5, tmax=1.5, decim=20)
info = epochs.info
del epochs

# %%
# To compute the source power for a frequency band, rather than each frequency
# separately, we average the CSD objects across frequencies.
csd = csd.mean()
csd_baseline = csd_baseline.mean()
csd_ers = csd_ers.mean()

# %%
# Computing DICS spatial filters using the CSD that was computed on the entire
# timecourse.
fwd = mne.read_forward_solution(fname_fwd)
filters = make_dics(info, fwd, csd, noise_csd=csd_baseline,
                    pick_ori='max-power', reduce_rank=True, real_filter=True)
del fwd

# %%
# Applying DICS spatial filters separately to the CSD computed using the
# baseline and the CSD computed during the ERS activity.
baseline_source_power, freqs = apply_dics_csd(csd_baseline, filters)
beta_source_power, freqs = apply_dics_csd(csd_ers, filters)

# %%
# Visualizing source power during ERS activity relative to the baseline power.
stc = beta_source_power / baseline_source_power
message = 'DICS source power in the 12-30 Hz frequency band'
brain = stc.plot(hemi='both', views='axial', subjects_dir=subjects_dir,
                 subject=subject, time_label=message)

# %%
# References
# ----------
# .. footbibliography::


text:
testdir = File.expand_path('..', __FILE__)
$LOAD_PATH.unshift(testdir) unless $LOAD_PATH.include?(testdir)
require 'test_helper'

require 'rets4r/loader'

class TestLoader < Minitest::Test
  def test_should_pass_records_to_block
    listings = []
    RETS4R::Loader.load(fixture('search_compact.xml').open) do |record|
      listings << record
    end

    assert_equal 2, listings.length
    assert_equal "Datum1", listings[0]['First']
    assert_equal "Datum2", listings[0]['Second']
    assert_equal "Datum3", listings[0]['Third']
    assert_equal "Datum4", listings[1]['First']
    assert_equal "Datum5", listings[1]['Second']
    assert_equal "Datum6", listings[1]['Third']

  end
end


text:
module Sprockets
  module Rails
    VERSION = "2.3.0"
  end
end