text:
package com.ctrip.xpipe.redis.meta.server.dcchange.impl;

import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.pool.XpipeNettyClientKeyedObjectPool;
import com.ctrip.xpipe.redis.core.metaserver.MetaServerConsoleService;
import com.ctrip.xpipe.redis.core.protocal.cmd.InfoReplicationComplementCommand;
import com.ctrip.xpipe.redis.core.protocal.pojo.MasterInfo;
import com.ctrip.xpipe.redis.core.protocal.pojo.RedisInfo;
import com.ctrip.xpipe.redis.core.protocal.pojo.SlaveInfo;
import com.ctrip.xpipe.redis.meta.server.cluster.CurrentClusterServer;
import com.ctrip.xpipe.redis.meta.server.dcchange.ExecutionLog;
import com.ctrip.xpipe.redis.meta.server.dcchange.PrimaryDcPrepareToChange;
import com.ctrip.xpipe.redis.meta.server.dcchange.RedisReadonly;
import com.ctrip.xpipe.redis.meta.server.dcchange.SentinelManager;
import com.ctrip.xpipe.redis.meta.server.meta.CurrentMetaManager;
import com.ctrip.xpipe.redis.meta.server.spring.MetaServerContextConfig;
import com.ctrip.xpipe.spring.AbstractSpringConfigContext;
import com.ctrip.xpipe.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author wenchao.meng
 *         <p>
 *         Aug 10, 2017
 */
@Component
public class DefaultPrimaryDcPrepareToChange implements PrimaryDcPrepareToChange{

    private Logger logger = LoggerFactory.getLogger(getClass());

    private  int waitForMasterInfoMilli = 2000;

    @Autowired
    private CurrentMetaManager currentMetaManager;

    @Resource(name = MetaServerContextConfig.CLIENT_POOL)
    private XpipeNettyClientKeyedObjectPool keyedObjectPool;

    @Resource(name = AbstractSpringConfigContext.SCHEDULED_EXECUTOR)
    private ScheduledExecutorService scheduled;

    @Autowired
    private SentinelManager sentinelManager;

    @Autowired
    private CurrentClusterServer currentClusterServer;

    @Override
    public MetaServerConsoleService.PreviousPrimaryDcMessage prepare(String clusterId, String shardId) {

        logger.info("[prepare]{}, {}", clusterId, shardId);

        MetaServerConsoleService.PreviousPrimaryDcMessage message = new MetaServerConsoleService.PreviousPrimaryDcMessage();
        ExecutionLog executionLog = new ExecutionLog(String.format("meta server:%s", currentClusterServer.getClusterInfo()));

        Pair<String, Integer> keeperMaster = currentMetaManager.getKeeperMaster(clusterId, shardId);
        message.setMasterAddr(new HostPort(keeperMaster.getKey(), keeperMaster.getValue()));
        executionLog.info("[prepare]" + keeperMaster);

        RedisInfo redisInfo = getInfoReplication(keeperMaster, executionLog);
        MasterInfo masterInfo = convert(redisInfo, executionLog);
        message.setMasterInfo(masterInfo);

        logger.info("[prepare]{}, {}, {}", keeperMaster, redisInfo, masterInfo);

        makeMasterReadOnly(clusterId, shardId, keeperMaster, true, executionLog);

        removeSentinel(clusterId, shardId, executionLog);

        message.setMessage(executionLog.getLog());
        return message;

    }

    @Override
    public MetaServerConsoleService.PreviousPrimaryDcMessage deprepare(String clusterId, String shardId) {

        logger.info("[deprepare]{}, {}", clusterId, shardId);

        MetaServerConsoleService.PreviousPrimaryDcMessage message = new MetaServerConsoleService.PreviousPrimaryDcMessage();
        ExecutionLog executionLog = new ExecutionLog(String.format("meta server:%s", currentClusterServer.getClusterInfo()));

        Pair<String, Integer> keeperMaster = currentMetaManager.getKeeperMaster(clusterId, shardId);
        message.setMasterAddr(new HostPort(keeperMaster.getKey(), keeperMaster.getValue()));
        executionLog.info("[deprepare]" + keeperMaster);

        makeMasterReadOnly(clusterId, shardId, keeperMaster, false, executionLog);

        addSentinel(clusterId, shardId, executionLog);

        message.setMessage(executionLog.getLog());
        return message;
    }

    private void addSentinel(String clusterId, String shardId, ExecutionLog executionLog) {

        logger.info("[addSentinel]{},{}", clusterId, shardId);
        Pair<String, Integer> keeperMaster = currentMetaManager.getKeeperMaster(clusterId, shardId);
        sentinelManager.addSentinel(clusterId, shardId, new HostPort(keeperMaster.getKey(), keeperMaster.getValue()), executionLog);

    }

    private void removeSentinel(String clusterId, String shardId, ExecutionLog executionLog) {

        logger.info("[removeSentinel]{},{}", clusterId, shardId);
        sentinelManager.removeSentinel(clusterId, shardId, executionLog);
    }

    private Pair<String, Integer> makeMasterReadOnly(String clusterId, String shardId, Pair<String, Integer> keeperMaster, boolean readOnly, ExecutionLog executionLog) {

        logger.info("[makeMasterReadOnly]{},{},{}", clusterId, shardId, readOnly);

        RedisReadonly redisReadOnly = RedisReadonly.create(keeperMaster.getKey(), keeperMaster.getValue(), keyedObjectPool, scheduled);
        try {
            executionLog.info(String.format("[makeMasterReadOnly][begin] %s:%s", keeperMaster, readOnly));
            if(readOnly){
                logger.info("[makeMasterReadOnly][readonly]{}", keeperMaster);
                redisReadOnly.makeReadOnly();
            }else{
                logger.info("[makeMasterReadOnly][writable]{}", keeperMaster);
                redisReadOnly.makeWritable();
            }
        } catch (Exception e) {
            logger.error("[makeMasterReadOnly]" + keeperMaster, e);
            executionLog.error(e.getMessage());
        }
        return keeperMaster;
    }

    public RedisInfo getInfoReplication(Pair<String, Integer> redisMaster, ExecutionLog executionLog) {

        InfoReplicationComplementCommand command = new InfoReplicationComplementCommand(
                keyedObjectPool.getKeyPool(new InetSocketAddress(redisMaster.getKey(), redisMaster.getValue())),
                scheduled
        );

        try {
            executionLog.info("[getInfoReplication]" + redisMaster);
            RedisInfo redisInfo = command.execute().get(waitForMasterInfoMilli, TimeUnit.MILLISECONDS);
            executionLog.info("[getInfoReplication]" + redisInfo);
            return redisInfo;
        } catch (InterruptedException e) {
            logger.error("[getInfoReplication]" + redisMaster, e);
            executionLog.error(e.getMessage());
        } catch (ExecutionException e) {
            logger.error("[getInfoReplication]" + redisMaster, e);
            executionLog.error(e.getMessage());
        } catch (TimeoutException e) {
            logger.error("[getInfoReplication]" + redisMaster, e);
            executionLog.error(e.getMessage());
        }
        return null;
    }

    private MasterInfo convert(RedisInfo redisInfo, ExecutionLog executionLog) {

        if(redisInfo == null){
            return null;
        }

        if(redisInfo instanceof MasterInfo){
            return (MasterInfo) redisInfo;
        }

        if(redisInfo instanceof SlaveInfo){
            executionLog.info("[convert][SlaveInfo]" + redisInfo);
            return ((SlaveInfo) redisInfo).toMasterInfo();
        }

        throw new IllegalStateException("unknown redisInfo:" + redisInfo);
    }

}


text:
package com.amazonaws.services.simplesystemsmanagement.model;

/**
 * Document Filter Key
 */
public enum DocumentFilterKey {

    Name("Name");

    private String value;

    private DocumentFilterKey(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *            real value
     * @return DocumentFilterKey corresponding to the value
     */
    public static DocumentFilterKey fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");

        } else if ("Name".equals(value)) {
            return DocumentFilterKey.Name;
        } else {
            throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
.. _phyluce: https://github.com/faircloth-lab/phyluce
.. _illumiprocessor: https://github.com/faircloth-lab/illumiprocessor/
.. _screen: http://www.gnu.org/software/screen/
.. _tmux: http://tmux.sourceforge.net/
.. _gzip: http://www.gzip.org/
.. _Casava: http://support.illumina.com/sequencing/sequencing_software/casava.ilmn
.. _bcl2fastq: https://support.illumina.com/downloads/bcl2fastq_conversion_software_184.ilmn
.. _fastx-toolkit: http://hannonlab.cshl.edu/fastx_toolkit/
.. _bartab: http://www.phyloware.com/Phyloware/XSTK.html
.. _velvet: http://www.ebi.ac.uk/~zerbino/velvet/
.. _ABySS: http://www.bcgsc.ca/platform/bioinfo/software/abyss
.. _Trinity: http://trinityrnaseq.sourceforge.net/
.. _homebrew: http://mxcl.github.com/homebrew/
.. _Amazon Web Services: http://aws.amazon.com/
.. _IDTDNA: http://www.idtdna.com/site
.. _uce-probe-sets: https://github.com/faircloth-lab/uce-probe-sets
.. _CloudForest: https://github.com/ngcrawford/CloudForest
.. _sqlite: http://www.sqlite.org
.. _sqlite-tutorial: http://www.sqlite.org/sqlite.html
.. _github: https://github.com/faircloth-lab/phyluce
.. _conda: http://docs.continuum.io/conda/
.. _multiprocessing: http://docs.python.org/2/library/multiprocessing.html
.. _Tree of Life: http://en.wikipedia.org/wiki/Tree_of_Life
.. _Phylogenomics: http://en.wikipedia.org/wiki/Phylogenomics
.. _CLI: http://en.wikipedia.org/wiki/Command-line_interface
.. _RAD-seq: http://en.wikipedia.org/wiki/Restriction_site_associated_DNA_markers
.. _RNA-seq: http://en.wikipedia.org/wiki/RNA-Seq
.. _amplicon sequencing: http://www.ncbi.nlm.nih.gov/pubmed/18274529
.. _unittests: http://en.wikipedia.org/wiki/Unit_testing
.. _Python: http://www.python.org
.. _cli branch: https://github.com/faircloth-lab/phyluce/tree/cli
.. _anaconda: http://docs.continuum.io/anaconda/install.html
.. _miniconda: http://repo.continuum.io/miniconda/
.. _CC-BY: http://creativecommons.org/licenses/by/4.0/
.. _virtualenv: http://www.virtualenv.org/
.. _MiSeq: http://www.illumina.com/systems/miseq.ilmn
.. _HiSeq: http://www.illumina.com/systems/hiseq_2500_1500.ilmn
.. _Illumina: http://www.illumina.com/
.. _lastz: http://www.bx.psu.edu/~rsharris/lastz/
.. _relational database: http://en.wikipedia.org/wiki/Relational_database
.. _FastQC: http://www.bioinformatics.babraham.ac.uk/projects/fastqc/
.. _symlinks: http://en.wikipedia.org/wiki/Symbolic_link
.. _symlink: http://en.wikipedia.org/wiki/Symbolic_link
.. _raxml: http://sco.h-its.org/exelixis/web/software/raxml/index.html
.. _exabayes: http://sco.h-its.org/exelixis/web/software/examl/index.html
.. _examl: http://sco.h-its.org/exelixis/web/software/exabayes/index.html
.. _mafft: http://mafft.cbrc.jp/alignment/software/
.. _muscle: http://www.drive5.com/muscle/
.. _gblocks: http://molevol.cmima.csic.es/castresana/Gblocks.html
.. _UCSC Genome Browser: https://genome.ucsc.edu/
.. _UCSC Genome Browser Downloads: https://genome.ucsc.edu/downloads
.. _Kent Source Archive: http://hgdownload.soe.ucsc.edu/admin/exe/
.. _NCBI: http://www.ncbi.nlm.nih.gov/
.. _stampy: http://www.well.ox.ac.uk/project-stampy
.. _samtools: http://www.htslib.org/
.. _BED: https://genome.ucsc.edu/FAQ/FAQformat.html#format1
.. _bedtools: http://bedtools.readthedocs.io/en/latest/
.. _BAM: https://samtools.github.io/hts-specs/SAMv1.pdf
.. _SAM: https://samtools.github.io/hts-specs/SAMv1.pdf
.. _Applied Genetics Laboratories: http://www.appliedgenetics.com/products/hybloc-competitor-dna/
.. _NCBI BioProject: https://www.ncbi.nlm.nih.gov/bioproject/
.. _bioconda: https://bioconda.github.io
.. _canu: https://github.com/marbl/canu
.. _longranger: https://support.10xgenomics.com/genome-exome/software/pipelines/latest/installation
.. _arks: https://github.com/bcgsc/arks
.. _links: https://github.com/bcgsc/LINKS
.. _tigmint: https://github.com/bcgsc/tigmint
.. _10X: https://www.10xgenomics.com
.. _Pilon: https://github.com/broadinstitute/pilon/wiki


text:
package org.jasig.cas.web.flow;

import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.ticket.InvalidTicketException;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.util.StringUtils;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.core.collection.LocalAttributeMap;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import javax.validation.constraints.NotNull;

/**
 * Action to generate a service ticket for a given Ticket Granting Ticket and
 * Service.
 *
 * @author Scott Battaglia
 * @since 3.0.0.4
 */
public final class GenerateServiceTicketAction extends AbstractAction {

    /** Instance of CentralAuthenticationService. */
    @NotNull
    private CentralAuthenticationService centralAuthenticationService;

    @Override
    protected Event doExecute(final RequestContext context) {
        final Service service = WebUtils.getService(context);
        final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);

        try {
            final ServiceTicket serviceTicketId = this.centralAuthenticationService
                .grantServiceTicket(ticketGrantingTicket, service);
            WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
            return success();
        } catch (final TicketException e) {
            if (e instanceof InvalidTicketException) {
                this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicket);
            }
            if (isGatewayPresent(context)) {
                return result("gateway");
            }

            return newEvent("error", e);
        }
    }

    public void setCentralAuthenticationService(
        final CentralAuthenticationService centralAuthenticationService) {
        this.centralAuthenticationService = centralAuthenticationService;
    }

    /**
     * Checks if gateway is present in the request params.
     *
     * @param context the context
     * @return true, if gateway present
     */
    protected boolean isGatewayPresent(final RequestContext context) {
        return StringUtils.hasText(context.getExternalContext()
            .getRequestParameterMap().get("gateway"));
    }

    /**
     * New event based on the id, which contains an error attribute referring to the exception occurred.
     *
     * @param id the id
     * @param error the error
     * @return the event
     */
    private Event newEvent(final String id, final Exception error) {
        return new Event(this, id, new LocalAttributeMap<Object>("error", error));
    }
}


text:
<?php
class ProjectsController extends AppController {

	var $name = 'Projects';
	var $components = array('Session');

	function view()
	{
		$id = 1;
		$this->set('project', $this->Project->read(null, $id));
	}

	function edit()
	{
		$id = 1;
		if (!empty($this->data))
		{
			if ($this->Project->save($this->data))
			{
				$this->Session->setFlash(sprintf(__('The %s has been saved', true), __('Project', true)));
				$this->redirect(array('action' => 'view'));
			}
			else
			{
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), __('Project', true)));
			}
		}
		if (empty($this->data))
		{
			$this->data = $this->Project->read(null, $id);
		}
	}
}
?>


text:
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.customtabs;

import android.os.Handler;

import org.chromium.base.Callback;
import org.chromium.base.ThreadUtils;
import org.chromium.chrome.browser.tab.Tab;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * This class contains logic for capturing navigation info at an appropriate time.
 *
 * We want to capture navigation information after both onload and first meaningful paint have
 * triggered. We add a slight delay to avoid capturing during CPU intensive periods.
 *
 * If a capture has not been taken after a long amount of time or when the Tab is hidden, we also
 * capture.
 */
public class NavigationInfoCaptureTrigger {
    private static final int ONLOAD_DELAY_MS = 1000;
    private static final int ONLOAD_LONG_DELAY_MS = 15000;
    private static final int ONHIDE_DELAY_MS = 1000;
    private static final int FMP_DELAY_MS = 3000;

    private final Callback<Tab> mCapture;
    private final Handler mUiThreadHandler = new Handler(ThreadUtils.getUiThreadLooper());
    private final List<Runnable> mPendingRunnables = new LinkedList<>();

    private boolean mOnloadTriggered;
    private boolean mFirstMeaningfulPaintTriggered;
    private boolean mCaptureTaken;

    public NavigationInfoCaptureTrigger(Callback<Tab> capture) {
        mCapture = capture;
    }

    /** Notifies that a page navigation has occurred and state should reset. */
    public void onNewNavigation() {
        mOnloadTriggered = false;
        mFirstMeaningfulPaintTriggered = false;
        mCaptureTaken = false;
        clearPendingRunnables();
    }

    /** Notifies that onload has occurred. */
    public void onLoadFinished(Tab tab) {
        mOnloadTriggered = true;
        captureDelayedIf(tab, () -> mFirstMeaningfulPaintTriggered, ONLOAD_DELAY_MS);
        captureDelayed(tab, ONLOAD_LONG_DELAY_MS);
    }

    /** Notifies that first meaningful paint has occurred. */
    public void onFirstMeaningfulPaint(Tab tab) {
        mFirstMeaningfulPaintTriggered = true;
        captureDelayedIf(tab, () -> mOnloadTriggered, FMP_DELAY_MS);
    }

    /** Notifies that the Tab has been hidden. */
    public void onHide(Tab tab) {
        captureDelayed(tab, ONHIDE_DELAY_MS);
    }

    private void clearPendingRunnables() {
        for (Runnable pendingRunnable: mPendingRunnables) {
            mUiThreadHandler.removeCallbacks(pendingRunnable);
        }
        mPendingRunnables.clear();
    }

    /** Posts a CaptureRunnable that will capture navigation info after the delay (ms). */
    private void captureDelayed(Tab tab, long delay) {
        captureDelayedIf(tab, () -> true, delay);
    }

    /**
     * Posts a CaptureRunnable that will capture navigation info after the delay (ms) if the check
     * passes.
     */
    private void captureDelayedIf(Tab tab, Callable<Boolean> check, long delay) {
        if (mCaptureTaken) return;
        Runnable runnable = new CaptureRunnable(tab, check);
        mPendingRunnables.add(runnable);
        mUiThreadHandler.postDelayed(runnable, delay);
    }

    /**
     * A Runnable that when executes ensures that no capture has already been taken and that the
     * check passes, then captures the navigation info and clears all other pending Runnables.
     */
    private class CaptureRunnable implements Runnable {
        private final Callable<Boolean> mCheck;
        private final Tab mTab;

        public CaptureRunnable(Tab tab, Callable<Boolean> check) {
            mCheck = check;
            mTab = tab;
        }

        @Override
        public void run() {
            assert !mCaptureTaken;

            try {
                if (!mCheck.call()) return;
            } catch (Exception e) {
                // In case mCheck.call throws an exception (which it shouldn't, but it's part of
                // Callable#call's signature).
                throw new RuntimeException(e);
            }

            mCapture.onResult(mTab);
            mCaptureTaken = true;

            clearPendingRunnables();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using EspaceClient.FrontOffice.Domaine;

namespace EspaceClient.BackOffice.Silverlight.Business.Depots
{
    /// <summary>
    /// Dépôt des droits
    /// </summary>
    public interface IDepotEdition
    {
        void GetEditions(Action<IEnumerable<EditionDto>> callback, Action<Exception> error);

        void GetAllEdition(Action<ObservableCollection<EditionDto>> callback, Action<Exception> error);

        void GetEditionById(long id, Action<EditionDto> callback, Action<Exception> error);

        void SaveEdition(EditionDto edition, Action<EditionDto> callback, Action<Exception> error);

        void DeleteEdition(EditionDto edition, Action<bool> callback, Action<Exception> error);

        void GetTypeRestitution(Action<ObservableCollection<TypeRestitutionEditionDto>> callback, Action<Exception> error);
    }
}


text:
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace Kubility
{

	/// <summary>
	/// 本地数据缓冲类(as ADT)
	/// </summary>
	public class ByteBuffer
	{
		public int DataCount
		{
			get
			{
				return Position;
			}
		}

		protected byte[] buffer;

		protected int Position;

//		public ByteBuffer()
//		{
//			buffer = new byte[1024];
//			Position = 0;
//		}

		public ByteBuffer(int size)
		{
			buffer = new byte[size];
			Position = 0;
		}

		public ByteBuffer(byte[] data)
		{
			buffer = new byte[data.Length];
			Position = data.Length;

			System.Array.Copy(data,0,buffer,0,data.Length);
		}

		public void ReSize(int size)
		{
			if(size <0)
			{
				LogMgr.LogError("Resize error");
				return;
			}

			if(size > buffer.Length)
			{
				System.Array.Resize(ref buffer,size);
			}
			else if( size < buffer.Length)
			{
				Position = size;

				System.Array.Resize(ref buffer,size+1);//at least 1 byte
				buffer[size] =0;//clear

			}
		}

		public virtual byte[] Read(int begin,int len)
		{
			if(len > DataCount-begin)
				len = DataCount-begin;

			byte[] bys = new byte[len];

			int i =0,j=0;
			for(i = begin; i < begin + len;++i,++j)
			{
				bys[j] = this.buffer[i];

			}
			if(DataCount-i- 1 >0)
			{
				System.Array.Copy(buffer,i,buffer,begin,DataCount-len);
				Position -= len;
			}
			else
			{
				ReSize(0);
			}
			return bys;
		}

		public void Copy(int sourceIndex, Array destinationArray, int destinationIndex, int length)
		{
			System.Array.Copy(buffer,sourceIndex,destinationArray,destinationIndex,length);
		}

		protected void IncreaseCapacity(int size)
		{
			byte[] newbuffer = new byte[size];
			Array.Copy(buffer,0,newbuffer,0,buffer.Length);
			buffer = null;
			buffer = newbuffer;

		}

		/// <summary>
		/// 清理指定大小的数据
		/// </summary>
		/// <param name="len">Length.</param>
		public void Clear(int len =-1)
		{
			if(len > buffer.Length)
			{
				//all clear
				Clear();
			}
			else if(len >0)
			{
				int newLen = buffer.Length -len;
				for (int i = 0; i < buffer.Length ; i++) //否则后面的数据往前移
				{
					if(i < newLen)
						buffer[i] = buffer[len + i];
					else
						buffer[i] =0;
				}
				Position -= len;

			}
			else
			{
				buffer = null;
				buffer = new byte[512];
				Position =0;
			}

		}

		public byte[] ConverToBytes(bool clean =false)
		{
			if(DataCount >0)
			{
				byte[] newbys = new byte[DataCount];
				Copy(0,newbys,0,DataCount);
				if(clean)
				{
					Clear(DataCount);
				}
				return newbys;
			}
			else
				return null;

		}

		public Stream ConverToStream()
		{
			return new MemoryStream(buffer);
		}

		#region operater

		public static ByteBuffer operator  +(ByteBuffer left,ByteBuffer right)
		{
			if(right != null)
			{
				int nextsize = right.DataCount + left.Position;
				if(nextsize > left.buffer.Length)
				{
					left.IncreaseCapacity(nextsize);
				}

				int endpos = left.Position +right.DataCount;
				for(int i=left.Position,j=0; i < endpos ;++i,++j)
				{
					left.buffer[i] = right.buffer[j];
				}
				right.Position =0;

				left.Position += right.DataCount;
			}

			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,byte[] right)
		{
			if(right != null)
			{
				int nextsize = right.Length + left.Position;
				if(nextsize > left.buffer.Length)
				{
					left.IncreaseCapacity(nextsize);
				}

				Array.Copy(right,0,left.buffer,left.Position,right.Length);
				left.Position += right.Length;
			}

			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,int right)
		{
			left +=BitConverter.GetBytes(right);
			return left;
		}

		public static ByteBuffer operator +(ByteBuffer left,Bool8 right)
		{
			left += right.GetBytes ();
			return left;
		}

		public static ByteBuffer operator +(ByteBuffer left,Bool32 right)
		{
			left += right.GetBytes ();
			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,float right)
		{
			left += BitConverter.GetBytes(right);
			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,double right)
		{
			left += BitConverter.GetBytes(right);
			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,short right)
		{
			left += BitConverter.GetBytes(right);
			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,long right)
		{
			left += BitConverter.GetBytes(right);
			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,uint right)
		{
			left += BitConverter.GetBytes(right);
			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,ushort right)
		{
			left += BitConverter.GetBytes(right);
			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,ulong right)
		{
			left += BitConverter.GetBytes(right);
			return left;
		}

		public static ByteBuffer operator  +(ByteBuffer left,string right)
		{
			left += right.Length;
			left += System.Text.Encoding.UTF8.GetBytes(right);
			return left;
		}

		#region Read
		public static explicit  operator Bool8 (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.BYTE_LEN)
			{
				byte[] tempBys = new byte[ByteStream.BYTE_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.BYTE_LEN);
				left.Clear(ByteStream.BYTE_LEN);
				return Bool8.ToBool8(tempBys);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return default(Bool8);
		}

		public static explicit  operator Bool32 (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.INT32_LEN)
			{
				byte[] tempBys = new byte[ByteStream.INT32_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.INT32_LEN);
				left.Clear(ByteStream.INT32_LEN);
				return Bool32.ToBool32(tempBys);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return false;
		}

		public static explicit  operator int (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.INT32_LEN)
			{
				byte[] tempBys = new byte[ByteStream.INT32_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.INT32_LEN);
				left.Clear(ByteStream.INT32_LEN);
				return BitConverter.ToInt32(tempBys,0);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return default(int);
		}

		public static explicit  operator uint (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.INT32_LEN)
			{
				byte[] tempBys = new byte[ByteStream.INT32_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.INT32_LEN);
				left.Clear(ByteStream.INT32_LEN);
				return BitConverter.ToUInt32(tempBys,0);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return default(UInt32);
		}

		public static explicit  operator short (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.SHORT16_LEN)
			{
				byte[] tempBys = new byte[ByteStream.SHORT16_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.SHORT16_LEN);
				left.Clear(ByteStream.SHORT16_LEN);
				return BitConverter.ToInt16(tempBys,0);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return default(short);
		}

		public static explicit  operator float (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.FLOAT_LEN)
			{
				byte[] tempBys = new byte[ByteStream.FLOAT_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.FLOAT_LEN);
				left.Clear(ByteStream.FLOAT_LEN);
				return BitConverter.ToSingle(tempBys,0);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return default(float);
		}

		public static explicit  operator double (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.DOUBLE_LEN)
			{
				byte[] tempBys = new byte[ByteStream.DOUBLE_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.DOUBLE_LEN);
				left.Clear(ByteStream.DOUBLE_LEN);
				return BitConverter.ToDouble(tempBys,0);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return default(double);
		}

		public static explicit  operator ushort (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.SHORT16_LEN)
			{
				byte[] tempBys = new byte[ByteStream.SHORT16_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.SHORT16_LEN);
				left.Clear(ByteStream.SHORT16_LEN);
				return BitConverter.ToUInt16(tempBys,0);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return default(ushort);
		}

		public static explicit  operator ulong (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.LONG_LEN)
			{
				byte[] tempBys = new byte[ByteStream.LONG_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.LONG_LEN);
				left.Clear(ByteStream.LONG_LEN);
				return BitConverter.ToUInt64(tempBys,0);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return default(ulong);
		}

		public static explicit  operator long (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.LONG_LEN)
			{
				byte[] tempBys = new byte[ByteStream.LONG_LEN];
				Array.Copy(left.buffer,0,tempBys,0,ByteStream.LONG_LEN);
				left.Clear(ByteStream.LONG_LEN);
				return BitConverter.ToInt64(tempBys,0);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return default(long);
		}

		public static explicit  operator string (ByteBuffer left)
		{
			if(left != null && left.DataCount >= ByteStream.INT32_LEN)
			{
				int strLen = (int)left;
				if(strLen == 0)
				{
					return null;
				}
				byte[] tempBys = new byte[strLen];
				Array.Copy(left.buffer,0,tempBys,0,strLen);
				left.Clear(strLen);
				return System.Text.Encoding.UTF8.GetString(tempBys);
			}
			LogMgr.LogError("Read from ByteBuffer Error");
			return null;
		}

		#endregion

		#endregion

	}
}


text:
@interface MACAdditionOperation ()

@property (nonatomic) NSNumber *firstNumber;
@property (nonatomic) NSNumber *secondNumber;
@property (nonatomic) NSNumber *sum;

@end

@implementation MACAdditionOperation

+ (SEL)designatedInitializer
{
    return @selector(initWithFirstNumber:secondNumber:);
}

+ (NSArray *)designatedInitializerArgumentNames
{
    return @[@"firstNumber", @"secondNumber"];
}

- (instancetype)initWithFirstNumber:(NSNumber *)firstNumber
                       secondNumber:(NSNumber *)secondNumber
{
    self = [super init];
    if (self) {
        _firstNumber = firstNumber;
        _secondNumber = secondNumber;
    }
    return self;
}

- (void)conductWork:(void (^)(NSError *))completion
{
    self.sum = @(self.firstNumber.doubleValue + self.secondNumber.doubleValue);
    completion(nil);
}

- (id)result
{
    return self.sum;
}

@end


text:
<?php

/**
 * Doctrine wrapper class.
 *
 * @author Jakub Argasiński <argasek@gmail.com>
 *
 */

class Void_Application_Doctrine {
	/**
	 * @var Doctrine_Manager
	 */
	private $_manager;

	/**
	 * @var Doctrine_Cli
	 */
	private $_cli;

	public function __construct(Doctrine_Manager $manager, Doctrine_Cli $cli) {
		$this->_manager = $manager;
		$this->_cli = $cli;
	}

	/**
	 * Returns
	 * @return Doctrine_Manager
	 */
	public function getManager() {
		return $this->_manager;
	}

	/**
	 *
	 * @return Doctrine_Cli
	 */
	public function getCli() {
		return $this->_cli;
	}

}


text:
package org.activiti.bpmn.model.parse;

import org.activiti.bpmn.model.BaseElement;

public class Warning {

  protected String warningMessage;
  protected String resource;
  protected int line;
  protected int column;

  public Warning(String warningMessage, String localName, int lineNumber, int columnNumber) {
    this.warningMessage = warningMessage;
    this.resource = localName;
    this.line = lineNumber;
    this.column = columnNumber;
  }

  public Warning(String warningMessage, BaseElement element) {
    this.warningMessage = warningMessage;
    this.resource = element.getId();
    line = element.getXmlRowNumber();
    column = element.getXmlColumnNumber();
  }

  public String toString() {
    return warningMessage + (resource != null ? " | " + resource : "") + " | line " + line + " | column " + column;
  }
}


text:
package io.quarkus.vertx.http.runtime.attribute;

import io.vertx.ext.web.RoutingContext;

public class RequestPathAttribute implements ExchangeAttribute {

    public static final String REQUEST_PATH = "%{REQUEST_PATH}";
    public static final String REQUEST_PATH_SHORT = "%R";

    public static final ExchangeAttribute INSTANCE = new RequestPathAttribute();

    private RequestPathAttribute() {

    }

    @Override
    public String readAttribute(final RoutingContext exchange) {
        return exchange.request().path();
    }

    @Override
    public void writeAttribute(final RoutingContext exchange, final String newValue) throws ReadOnlyAttributeException {
        throw new ReadOnlyAttributeException();
    }

    public static final class Builder implements ExchangeAttributeBuilder {

        @Override
        public String name() {
            return "Request Path";
        }

        @Override
        public ExchangeAttribute build(final String token) {
            return token.equals(REQUEST_PATH) || token.equals(REQUEST_PATH_SHORT) ? INSTANCE : null;
        }

        @Override
        public int priority() {
            return 0;
        }
    }
}


text:
<?php

$token	= getRandomString();
$db		= Database::get();

$fleetResult	= $db->update("UPDATE %%FLEETS_EVENT%% SET `lock` = :token WHERE `lock` IS NULL AND `time` <= :time;", array(
	':time'		=> TIMESTAMP,
	':token'	=> $token
));

if($db->rowCount() !== 0) {
	require 'includes/classes/class.FlyingFleetHandler.php';

	$fleetObj	= new FlyingFleetHandler();
	$fleetObj->setToken($token);
	$fleetObj->run();

	$db->update("UPDATE %%FLEETS_EVENT%% SET `lock` = NULL WHERE `lock` = :token;", array(
		':token' => $token
	));
}


text:
'use strict';

describe('Controller: MainController', function () {

  // load the controller's module
  beforeEach(module('<%= scriptAppName %>'));

  var MainController, scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    MainController = $controller('MainController', {
      $scope: scope
    });
  }));

  it('should exist', function () {
    MainController.should.be.instanceof(Object);
  });
});


text:
package ciris

import cats.data.Chain
import cats.Eq
import cats.laws.discipline.ContravariantTests
import cats.laws.discipline.MonadErrorTests
import cats.syntax.all._
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Gen
import org.scalacheck.Prop.forAll
import org.scalacheck.Test
import scala.concurrent.duration.{Duration, FiniteDuration}
import scala.util.Try

final class ConfigDecoderSpec extends DisciplineSuite with Generators {
  implicit def configDecoderEq[A, B](
    implicit arb: Arbitrary[A],
    eq: Eq[B]
  ): Eq[ConfigDecoder[A, B]] =
    Eq.instance { (d1, d2) =>
      Test.check {
        forAll { (a: A) =>
          d1.decode(None, a) === d2.decode(None, a)
        }
      }(_ => scalaCheckTestParameters).passed
    }

  property("ConfigDecoder.as") {
    forAll { (key: Option[ConfigKey], s: String) =>
      val expected = ConfigDecoder[String, Int].decode(key, s)
      val actual = ConfigDecoder[String].as[Int].decode(key, s)
      actual === expected
    }
  }

  property("ConfigDecoder.bigDecimal.success") {
    forAll { (bigDecimal: BigDecimal) =>
      ConfigDecoder[String, BigDecimal].decode(None, bigDecimal.toString) === bigDecimal.asRight
    }
  }

  property("ConfigDecoder.bigDecimal.failure") {
    val gen =
      arbitrary[String].filter(s => Try(BigDecimal(s)).isFailure)

    forAll(gen) { s =>
      ConfigDecoder[String, BigDecimal].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.bigInt.success") {
    forAll { (bigInt: BigInt) =>
      ConfigDecoder[String, BigInt].decode(None, bigInt.toString) === bigInt.asRight
    }
  }

  property("ConfigDecoder.bigInt.failure") {
    val gen =
      arbitrary[String].filter(s => Try(BigInt(s)).isFailure)

    forAll(gen) { s =>
      ConfigDecoder[String, BigInt].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.boolean.success") {
    val genBoolean =
      Gen.oneOf(
        "true",
        "yes",
        "on",
        "false",
        "no",
        "off"
      )

    forAll(genBoolean) { boolean =>
      ConfigDecoder[String, Boolean].decode(None, boolean.toString).isRight
    }
  }

  property("ConfigDecoder.boolean.failure") {
    def isBoolean(s: String) =
      s.toLowerCase() match {
        case "true" | "yes" | "on"  => true
        case "false" | "no" | "off" => true
        case _                      => false
      }

    val gen =
      arbitrary[String].filterNot(isBoolean)

    forAll(gen) { s =>
      ConfigDecoder[String, Boolean].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.byte.success") {
    forAll { (byte: Byte) =>
      ConfigDecoder[String, Byte].decode(None, byte.toString) === byte.asRight
    }
  }

  property("ConfigDecoder.byte.failure") {
    val gen =
      arbitrary[String].filter(s => Try(s.toByte).isFailure)

    forAll(gen) { s =>
      ConfigDecoder[String, Byte].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.char.success") {
    forAll { (char: Char) =>
      ConfigDecoder[String, Char].decode(None, char.toString) === char.asRight
    }
  }

  property("ConfigDecoder.char.failure") {
    val gen =
      arbitrary[String].filter(_.length =!= 1)

    forAll(gen) { s =>
      ConfigDecoder[String, Char].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.double.success") {
    forAll { (double: Double) =>
      ConfigDecoder[String, Double].decode(None, double.toString) === double.asRight
    }
  }

  property("ConfigDecoder.double.success percent") {
    forAll { (double: Double) =>
      ConfigDecoder[String, Double]
        .decode(None, double.toString ++ "%") === (double / 100f).asRight
    }
  }

  property("ConfigDecoder.double.failure") {
    val gen =
      arbitrary[String].filter(s => Try(s.toDouble).isFailure)

    forAll(gen) { s =>
      ConfigDecoder[String, Double].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.duration.success") {
    val gen =
      arbitrary[Duration]
        .filterNot(_ eq Duration.Undefined)
        .filter(duration => Try(Duration(duration.toString)).isSuccess)

    forAll(gen) { duration =>
      val expected = Right(Duration(duration.toString))
      ConfigDecoder[String, Duration].decode(None, duration.toString) == expected
    }
  }

  property("ConfigDecoder.duration.failure") {
    val gen =
      arbitrary[String].filter(s => Try(Duration(s)).isFailure)

    forAll(gen) { s =>
      assert(ConfigDecoder[String, Duration].decode(None, s).isLeft)
    }
  }

  property("ConfigDecoder.finiteDuration.success") {
    val gen =
      arbitrary[FiniteDuration]
        .filter(d => Try(Duration(d.toString)).isSuccess)

    forAll { (finiteDuration: FiniteDuration) =>
      val actual = ConfigDecoder[String, FiniteDuration].decode(None, finiteDuration.toString)
      val expected = Right(Duration(finiteDuration.toString))
      actual == expected
    }
  }

  property("ConfigDecoder.finiteDuration.failure") {
    val gen =
      arbitrary[String].filter(s => Try(Duration(s)).isFailure)

    forAll(gen) { s =>
      ConfigDecoder[String, FiniteDuration].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.float.success") {
    forAll { (float: Float) =>
      ConfigDecoder[String, Float].decode(None, float.toString) === float.asRight
    }
  }

  property("ConfigDecoder.float.success percent") {
    forAll { (float: Float) =>
      ConfigDecoder[String, Float].decode(None, float.toString ++ "%") === (float / 100f).asRight
    }
  }

  property("ConfigDecoder.float.failure") {
    val gen =
      arbitrary[String].filter(s => Try(s.toFloat).isFailure)

    forAll(gen) { s =>
      ConfigDecoder[String, Float].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.int.success") {
    forAll { (int: Int) =>
      ConfigDecoder[String, Int].decode(None, int.toString) === int.asRight
    }
  }

  property("ConfigDecoder.int.failure") {
    val gen =
      arbitrary[String].filter(s => Try(s.toInt).isFailure)

    forAll(gen) { s =>
      ConfigDecoder[String, Int].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.long.success") {
    forAll { (long: Long) =>
      ConfigDecoder[String, Long].decode(None, long.toString) === long.asRight
    }
  }

  property("ConfigDecoder.long.failure") {
    val gen =
      arbitrary[String].filter(s => Try(s.toLong).isFailure)

    forAll(gen) { s =>
      ConfigDecoder[String, Long].decode(None, s).isLeft
    }
  }

  checkAll(
    "ConfigDecoder",
    ContravariantTests[ConfigDecoder[*, String]].contravariant[String, String, String]
  )

  checkAll(
    "ConfigDecoder",
    MonadErrorTests[ConfigDecoder[String, *], ConfigError].monadError[String, String, String]
  )

  property("ConfigDecoder.short.success") {
    forAll { (short: Short) =>
      ConfigDecoder[String, Short].decode(None, short.toString) === short.asRight
    }
  }

  property("ConfigDecoder.short.failure") {
    val gen =
      arbitrary[String].filter(s => Try(s.toShort).isFailure)

    forAll(gen) { s =>
      ConfigDecoder[String, Short].decode(None, s).isLeft
    }
  }

  property("ConfigDecoder.toString") {
    forAll { (decoder: ConfigDecoder[String, String]) =>
      decoder.toString.startsWith("ConfigDecoder$")
    }
  }

  property("ConfigDecoder.redacted.nonSensitive") {
    forAll { (key: Option[ConfigKey], value: String) =>
      val decoder =
        ConfigDecoder.instance[String, String] { (key, value) =>
          Left(ConfigError("message"))
        }

      val expected = "message"
      val actual = decoder.redacted.decode(key, value)
      actual.leftMap(_.messages) == Left(Chain.one(expected))
    }
  }

  property("ConfigDecoder.redacted.sensitive") {
    forAll { (key: Option[ConfigKey], value: String) =>
      val decoder =
        ConfigDecoder.instance[String, String] { (key, value) =>
          Left(ConfigError.sensitive("message", "redacted"))
        }

      val expected = "redacted"
      val actual = decoder.redacted.decode(key, value)
      actual.leftMap(_.messages) == Left(Chain.one(expected))
    }
  }
}


text:
habitchainer
============

DBC utility


text:
declare @Result tinyint;
select @Result=HAS_PERMS_BY_NAME('$principal$', 'USER', 'IMPERSONATE')

if (@Result<>1)
begin
	print '  Inconclusive: the user ' + CURRENT_USER + ' cannot impersonate $principal$'
end
else
begin
	set @Result=0;
	begin try
		execute as user='$principal$';
		set @Result=1;
	end try
    begin catch
		if (error_number()=916)
		begin
			print '  Inconclusive: the user $principal$ doesn''t exit or cannot log to the database $database.name$ on $database.server$';
		end
		else
		begin
			print '  Inconclusive: Error = ' + ERROR_MESSAGE();
		end
	end catch

	if (@Result=1)
	begin
$securables:{securable |

		select @Result=HAS_PERMS_BY_NAME('$securable.name$', '$securable.type$', '$securable.permission$');
		select '$database.server$', '$database.name$','$securable.name$', '$securable.type$', '$securable.permission$', '$principal$', @Result;

		if (@Result=1)
		begin
			print '  Success: the permission $securable.permission$ was granted on $securable.type$::$securable.name$ for principal $principal$'
		end
		else
		begin
			print '  Failure: the permission $securable.permission$ was NOT granted on $securable.type$::$securable.name$ for principal $principal$'
		end

		revert;

}$
	end
end


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using NakedFramework.Architecture.Component;
using NakedFramework.Architecture.FacetFactory;
using NakedFramework.Architecture.Reflect;
using NakedFramework.Architecture.Spec;
using NakedFramework.Architecture.SpecImmutable;
using NakedFramework.ParallelReflector.FacetFactory;
using NOF2.Reflector.FacetFactory;

namespace NOF2.Reflector.Reflect;

public sealed class NOF2FacetFactorySet : IFacetFactorySet {
    private readonly IList<IMethodIdentifyingFacetFactory> actionIdentifyingFactories;
    private readonly IDictionary<FeatureType, IList<INOF2FacetFactoryProcessor>> factoriesByFeatureType = new Dictionary<FeatureType, IList<INOF2FacetFactoryProcessor>>();

    /// <summary>
    ///     All registered <see cref="IFacetFactory" />s that implement
    ///     <see cref="IMethodFilteringFacetFactory" />
    /// </summary>
    /// <para>
    ///     Used within <see cref="IFacetFactorySet.Filters(MethodInfo, IClassStrategy)" />
    /// </para>
    private readonly IList<IMethodFilteringFacetFactory> methodFilteringFactories;

    /// <summary>
    ///     All registered <see cref="IFacetFactory" />s that implement
    ///     <see cref="IPropertyFilteringFacetFactory" />
    /// </summary>
    /// <para>
    ///     Used within <see cref="IFacetFactorySet.Filters(PropertyInfo, IClassStrategy)" />
    /// </para>
    private readonly IList<IPropertyFilteringFacetFactory> propertyFilteringFactories;

    /// <summary>
    ///     All registered <see cref="IFacetFactory" />s that implement
    ///     <see
    ///         cref="IPropertyOrCollectionIdentifyingFacetFactory" />
    /// </summary>
    /// <para>
    ///     Used within <see cref="IFacetFactorySet.Recognizes" />
    /// </para>
    private readonly IList<IPropertyOrCollectionIdentifyingFacetFactory> propertyOrCollectionIdentifyingFactories;

    public NOF2FacetFactorySet(IEnumerable<INOF2FacetFactoryProcessor> factories) {
        var allFactories = factories.ToList();
        allFactories.Sort();

        Prefixes = allFactories.OfType<IMethodPrefixBasedFacetFactory>().SelectMany(prefixfactory => prefixfactory.Prefixes).ToArray();

        foreach (FeatureType featureType in System.Enum.GetValues(typeof(FeatureType))) {
            factoriesByFeatureType[featureType] = allFactories.Where(f => f.FeatureTypes.HasFlag(featureType)).ToArray();
        }

        methodFilteringFactories = allFactories.OfType<IMethodFilteringFacetFactory>().ToArray();
        propertyFilteringFactories = allFactories.OfType<IPropertyFilteringFacetFactory>().ToArray();
        propertyOrCollectionIdentifyingFactories = allFactories.OfType<IPropertyOrCollectionIdentifyingFacetFactory>().ToArray();
        actionIdentifyingFactories = allFactories.OfType<IMethodIdentifyingFacetFactory>().ToArray();
    }

    private string[] Prefixes { get; }

    private IList<INOF2FacetFactoryProcessor> GetFactoryByFeatureType(FeatureType featureType) => factoriesByFeatureType[featureType];

    #region IFacetFactorySet Members

    public IList<PropertyInfo> FindCollectionProperties(IList<PropertyInfo> candidates, IClassStrategy classStrategy) => propertyOrCollectionIdentifyingFactories.SelectMany(fact => fact.FindCollectionProperties(candidates, classStrategy)).ToArray();

    public IList<PropertyInfo> FindProperties(IList<PropertyInfo> candidates, IClassStrategy classStrategy) => propertyOrCollectionIdentifyingFactories.SelectMany(fact => fact.FindProperties(candidates, classStrategy)).ToArray();

    public IList<MethodInfo> FindActions(IList<MethodInfo> candidates, IClassStrategy classStrategy) => actionIdentifyingFactories.SelectMany(fact => fact.FindActions(candidates, classStrategy)).ToArray();

    /// <summary>
    ///     Whether this method is recognized (and should be ignored) by
    ///     any of the registered <see cref="IFacetFactory" />
    /// </summary>
    /// <para>
    ///     Checks:
    /// </para>
    /// <list type="bullet">
    ///     <item>
    ///         the method's prefix against the prefixes supplied by any <see cref="IMethodPrefixBasedFacetFactory" />
    ///     </item>
    ///     <item>
    ///         the method against any <see cref="IMethodFilteringFacetFactory" />
    ///     </item>
    /// </list>
    /// <para>
    ///     The design of <see cref="IMethodPrefixBasedFacetFactory" /> (whereby this
    ///     facet factory set does the work) is a slight performance optimization
    ///     for when there are multiple facet factories that search for the
    ///     same prefix.
    /// </para>
    public bool Filters(MethodInfo method, IClassStrategy classStrategy) => methodFilteringFactories.Any(factory => factory.Filters(method, classStrategy));

    public bool Filters(PropertyInfo property, IClassStrategy classStrategy) => propertyFilteringFactories.Any(factory => factory.Filters(property, classStrategy));

    public bool Recognizes(MethodInfo method) => Prefixes.Any(prefix => method.Name.StartsWith(prefix, StringComparison.Ordinal));

    public IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
        if (type.IsInterface) {
            foreach (var facetFactory in GetFactoryByFeatureType(FeatureType.Interfaces)) {
                metamodel = facetFactory.Process(reflector, type, methodRemover, specification, metamodel);
            }
        }
        else {
            foreach (var facetFactory in GetFactoryByFeatureType(FeatureType.Objects)) {
                metamodel = facetFactory.Process(reflector, type, methodRemover, specification, metamodel);
            }
        }

        return metamodel;
    }

    public IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, MethodInfo method, IMethodRemover methodRemover, ISpecificationBuilder specification, FeatureType featureType, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
        foreach (var facetFactory in GetFactoryByFeatureType(featureType)) {
            metamodel = facetFactory.Process(reflector, method, methodRemover, specification, metamodel);
        }

        return metamodel;
    }

    public IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, PropertyInfo property, IMethodRemover methodRemover, ISpecificationBuilder specification, FeatureType featureType, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
        foreach (var facetFactory in GetFactoryByFeatureType(featureType)) {
            metamodel = facetFactory.Process(reflector, property, methodRemover, specification, metamodel);
        }

        return metamodel;
    }

    public IImmutableDictionary<string, ITypeSpecBuilder> ProcessParams(IReflector reflector, MethodInfo method, int paramNum, ISpecificationBuilder specification, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
        foreach (var facetFactory in GetFactoryByFeatureType(FeatureType.ActionParameters)) {
            metamodel = facetFactory.ProcessParams(reflector, method, paramNum, specification, metamodel);
        }

        return metamodel;
    }

    #endregion
}


text:
require 'spec_helper'

describe 'spree/admin/google_trusted_store_settings/edit.html.erb', settings_spec: true, story_159: true do
  before(:each) do
    allow(view.spree).to receive(:admin_general_settings_path)
      .and_return 'http://duhh.com/'
    allow(view.spree).to receive(:google_trusted_store_shipment_feed_url)
      .and_return 'shipment feed url'
    allow(view.spree).to receive(:google_trusted_store_cancelation_feed_url)
      .and_return 'cancelation feed url'
  end

  it 'displays a text field for account_id and default_locale' do
    assign(:google_trusted_store_setting, Spree::GoogleTrustedStoreSetting.create)
    render template: 'spree/admin/google_trusted_store_settings/edit'

    expect(rendered).to have_css 'input[type="text"][name="google_trusted_store_setting[account_id]"]'
    expect(rendered).to have_css 'input[type="text"][name="google_trusted_store_setting[default_locale]"]'
  end

  context 'when a user has sufficient permissions' do
    # TODO actually require permissions

    it 'shows the url for shipment automatic upload', feed_spec: true do
      assign(:google_trusted_store_setting, Spree::GoogleTrustedStoreSetting.create)
      render template: 'spree/admin/google_trusted_store_settings/edit'

      expect(rendered).to include 'shipment feed url'
    end

    it 'shows the url for cancelation automatic upload', feed_spec: true do
      assign(:google_trusted_store_setting, Spree::GoogleTrustedStoreSetting.create)
      render template: 'spree/admin/google_trusted_store_settings/edit'

      expect(rendered).to include 'cancelation feed url'
    end
  end
end


text:
@interface VXDataManager : NSObject

@property (strong, nonatomic) NSManagedObjectContext *context;
@property (strong, nonatomic) NSManagedObjectContext *backgroundContext;
@property (strong, nonatomic) NSManagedObjectModel *model;
@property (strong, nonatomic) NSPersistentStoreCoordinator *persistentStore;

@property (strong, nonatomic) NSString *databaseName;

+ (VXDataManager *)sharedInstance;
- (VXDataManager *)init NS_DESIGNATED_INITIALIZER;
- (BOOL)copyStoreWithOverwrite:(BOOL)pOverwriteExisting;
@property (NS_NONATOMIC_IOSONLY, getter=isMigrationNecessary, readonly) BOOL migrationNecessary;
- (void)save;
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL;
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSURL *storeURL;
@end


text:
#ifndef ARDUINO_PIXEL_MODE_RAINBOW_BASE_H
#define ARDUINO_PIXEL_MODE_RAINBOW_BASE_H

#include "mode/mode_base.h"

namespace arduino_pixel {
namespace mode {

class RainbowBase : public ModeBase {
 public:
  RainbowBase(const int& num_leds, const unsigned long& period)
      : ModeBase(num_leds),
        color_(0, 0, 0),
        alpha_(0.5f),
        period_(period),
        offset_(0) {
    pixels_ = new Color[num_leds_];
    last_update_time_ = millis();
  }

  virtual ~RainbowBase() { delete[] pixels_; }

  virtual void init() override { setPixels(); }

  virtual bool update() override {
    unsigned long current_time = millis();
    if ((unsigned long)(current_time - last_update_time_) < period_) return false;
    setPixels();
    last_update_time_ = current_time;
    return true;
  }

  virtual const Color& getPixel(int idx) const override { return pixels_[idx]; }

  virtual const Color& getColor(int idx = 0) const override { return color_; }

  virtual void setColor(const Color& color, int idx = 0) override {
    color_ = color;
    alpha_ = 0.2989f * color.red + 0.5870f * color.green + 0.1140f * color.blue;
    alpha_ = alpha_ / 255.f;
  }

  virtual Mode getModeType() const override = 0;

  virtual String getMode() const override = 0;

 protected:
  virtual void setPixels() = 0;

  /**
   * \brief Turns the requested value into a color.
   * \details The colors are the cycle r - g - b.
   * \note The code is borrowsed from the strandtest example of the
   * Adafruit_NeoPixel library.
   * \param[in] pos a value.
   * \return A color.
   */
  Color wheel(byte pos) {
    pos = 255 - pos;
    if (pos < 85) {
      return Color(255 - pos * 3, 0, pos * 3, alpha_);
    } else if (pos < 170) {
      pos -= 85;
      return Color(0, pos * 3, 255 - pos * 3, alpha_);
    } else {
      pos -= 170;
      return Color(pos * 3, 255 - pos * 3, 0, alpha_);
    }
  }

  Color color_;
  float alpha_;           // Defines the brightness ([0.0,1.0]) of the rainbow
  unsigned long period_;  // The period at which the rainbow moves

  Color* pixels_;

  unsigned long last_update_time_;
  uint16_t offset_;
};

}  // namespace mode
}  // namespace arduino_pixel

#endif  // ARDUINO_PIXEL_MODE_RAINBOW_BASE_H


text:
Display a placeholder while the content is loading.

Example

<div ons-loading-placeholder="page.html">
  Loading...
</div>

Attributes

              ons-loading-placeholder
              The url of the page to load.

See also

Other utility APIs


text:
use strict;
use warnings;
use Libssh::Session qw(:all);

my $ssh_host = "127.0.0.1";
my $ssh_port = 22;
my $ssh_user = "root";
my $ssh_pass = "centreon";

my $session = Libssh::Session->new();
if ($session->options(host => $ssh_host, port => $ssh_port, user => $ssh_user) != SSH_OK) {
    print $session->error() . "\n";
    exit(1);
}

if ($session->connect() != SSH_OK) {
    print $session->error() . "\n";
    exit(1);
}

$session->auth_none(); # prerequisite for getting auth_list
unless ($session->auth_list() & SSH_AUTH_METHOD_INTERACTIVE) {
	print "SSH server doesn't support keyboard-interactive authentication.\n";
	exit(1);
}

my $ret = $session->auth_kbdint();
while ($ret == SSH_AUTH_INFO) {
	my $name        = $session->auth_kbdint_getname();
	my $instruction = $session->auth_kbdint_getinstruction();
	my $nprompts    = $session->auth_kbdint_getnprmopts();

	print "$name\n"        if (defined $name);
	print "$instruction\n" if (defined $instruction);

	for (my $i = 0; $i < $nprompts; $i++) {
		my $answer;
		my $prompt = $session->auth_kbdint_getprompt(index => $i);
		if ($prompt->{text} =~ /Password:/) {
			$answer = $ssh_pass;
		} else {
			print "$prompt " if ($prompt->{echo});
			chomp($answer = <STDIN>);
			$answer .= "\0";
		}
		if ($session->auth_kbdint_setanswer(index => $i, answer => $answer) < 0) {
			printf("setting answer issue: %s\n", $session->error());
			exit(1);
		}
	}
	$ret = $session->auth_kbdint();
}

if ($ret == SSH_AUTH_SUCCESS) {
	print "== authentification succeeded\n";
} else {
	my $error = $session->error();
	print "$error\n" if ($error);
	print "== failed to authenticate: rc = $ret\n";
	exit(1);
}

exit(0);


text:
import random, math, sys, time

SIZE = 9
GAMES = 200
KOMI = 7.5
EMPTY, WHITE, BLACK = 0, 1, 2
SHOW = {EMPTY: '.', WHITE: 'o', BLACK: 'x'}
PASS = -1
MAXMOVES = SIZE*SIZE*3
TIMESTAMP = 0
MOVES = 0

def to_pos(x,y):
    return y * SIZE + x

def to_xy(pos):
    y, x = divmod(pos, SIZE)
    return x, y

class Square:
    def __init__(self, board, pos):
        self.board = board
        self.pos = pos
        self.timestamp = TIMESTAMP
        self.removestamp = TIMESTAMP
        self.zobrist_strings = [random.randrange(sys.maxint) for i in range(3)]

    def set_neighbours(self):
        x, y = self.pos % SIZE, self.pos / SIZE;
        self.neighbours = []
        for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            newx, newy = x + dx, y + dy
            if 0 <= newx < SIZE and 0 <= newy < SIZE:
                self.neighbours.append(self.board.squares[to_pos(newx, newy)])

    def move(self, color):
        global TIMESTAMP, MOVES
        TIMESTAMP += 1
        MOVES += 1
        self.board.zobrist.update(self, color)
        self.color = color
        self.reference = self
        self.ledges = 0
        self.used = True
        for neighbour in self.neighbours:
            neighcolor = neighbour.color
            if neighcolor == EMPTY:
                self.ledges += 1
            else:
                neighbour_ref = neighbour.find(update=True)
                if neighcolor == color:
                    if neighbour_ref.reference.pos != self.pos:
                        self.ledges += neighbour_ref.ledges
                        neighbour_ref.reference = self
                    self.ledges -= 1
                else:
                    neighbour_ref.ledges -= 1
                    if neighbour_ref.ledges == 0:
                        neighbour.remove(neighbour_ref)
        self.board.zobrist.add()

    def remove(self, reference, update=True):
        self.board.zobrist.update(self, EMPTY)
        self.removestamp = TIMESTAMP
        if update:
            self.color = EMPTY
            self.board.emptyset.add(self.pos)
#            if color == BLACK:
#                self.board.black_dead += 1
#            else:
#                self.board.white_dead += 1
        for neighbour in self.neighbours:
            if neighbour.color != EMPTY and neighbour.removestamp != TIMESTAMP:
                neighbour_ref = neighbour.find(update)
                if neighbour_ref.pos == reference.pos:
                    neighbour.remove(reference, update)
                else:
                    if update:
                        neighbour_ref.ledges += 1

    def find(self, update=False):
       reference = self.reference
       if reference.pos != self.pos:
           reference = reference.find(update)
           if update:
               self.reference = reference
       return reference

    def __repr__(self):
        return repr(to_xy(self.pos))

class EmptySet:
    def __init__(self, board):
        self.board = board
        self.empties = range(SIZE*SIZE)
        self.empty_pos = range(SIZE*SIZE)

    def random_choice(self):
        choices = len(self.empties)
        while choices:
            i = int(random.random()*choices)
            pos = self.empties[i]
            if self.board.useful(pos):
                return pos
            choices -= 1
            self.set(i, self.empties[choices])
            self.set(choices, pos)
        return PASS

    def add(self, pos):
        self.empty_pos[pos] = len(self.empties)
        self.empties.append(pos)

    def remove(self, pos):
        self.set(self.empty_pos[pos], self.empties[len(self.empties)-1])
        self.empties.pop()

    def set(self, i, pos):
        self.empties[i] = pos
        self.empty_pos[pos] = i

class ZobristHash:
    def __init__(self, board):
        self.board = board
        self.hash_set = set()
        self.hash = 0
        for square in self.board.squares:
            self.hash ^= square.zobrist_strings[EMPTY]
        self.hash_set.clear()
        self.hash_set.add(self.hash)

    def update(self, square, color):
        self.hash ^= square.zobrist_strings[square.color]
        self.hash ^= square.zobrist_strings[color]

    def add(self):
        self.hash_set.add(self.hash)

    def dupe(self):
        return self.hash in self.hash_set

class Board:
    def __init__(self):
        self.squares = [Square(self, pos) for pos in range(SIZE*SIZE)]
        for square in self.squares:
            square.set_neighbours()
        self.reset()

    def reset(self):
        for square in self.squares:
            square.color = EMPTY
            square.used = False
        self.emptyset = EmptySet(self)
        self.zobrist = ZobristHash(self)
        self.color = BLACK
        self.finished = False
        self.lastmove = -2
        self.history = []
        self.white_dead = 0
        self.black_dead = 0

    def move(self, pos):
        square = self.squares[pos]
        if pos != PASS:
            square.move(self.color)
            self.emptyset.remove(square.pos)
        elif self.lastmove == PASS:
            self.finished = True
        if self.color == BLACK: self.color = WHITE
        else: self.color = BLACK
        self.lastmove = pos
        self.history.append(pos)

    def random_move(self):
        return self.emptyset.random_choice()

    def useful_fast(self, square):
        if not square.used:
            for neighbour in square.neighbours:
                if neighbour.color == EMPTY:
                    return True
        return False

    def useful(self, pos):
        global TIMESTAMP
        TIMESTAMP += 1
        square = self.squares[pos]
        if self.useful_fast(square):
            return True
        old_hash = self.zobrist.hash
        self.zobrist.update(square, self.color)
        empties = opps = weak_opps = neighs = weak_neighs = 0
        for neighbour in square.neighbours:
            neighcolor = neighbour.color
            if neighcolor == EMPTY:
                empties += 1
                continue
            neighbour_ref = neighbour.find()
            if neighbour_ref.timestamp != TIMESTAMP:
                if neighcolor == self.color:
                    neighs += 1
                else:
                    opps += 1
                neighbour_ref.timestamp = TIMESTAMP
                neighbour_ref.temp_ledges = neighbour_ref.ledges
            neighbour_ref.temp_ledges -= 1
            if neighbour_ref.temp_ledges == 0:
                if neighcolor == self.color:
                    weak_neighs += 1
                else:
                    weak_opps += 1
                    neighbour_ref.remove(neighbour_ref, update=False)
        dupe = self.zobrist.dupe()
        self.zobrist.hash = old_hash
        strong_neighs = neighs-weak_neighs
        strong_opps = opps-weak_opps
        return not dupe and \
               (empties or weak_opps or (strong_neighs and (strong_opps or weak_neighs)))

    def useful_moves(self):
        return [pos for pos in self.emptyset.empties if self.useful(pos)]

    def replay(self, history):
        for pos in history:
            self.move(pos)

    def score(self, color):
        if color == WHITE:
            count = KOMI + self.black_dead
        else:
            count = self.white_dead
        for square in self.squares:
            squarecolor = square.color
            if squarecolor == color:
                count += 1
            elif squarecolor == EMPTY:
                surround = 0
                for neighbour in square.neighbours:
                    if neighbour.color == color:
                        surround += 1
                if surround == len(square.neighbours):
                    count += 1
        return count

    def check(self):
       for square in self.squares:
           if square.color == EMPTY:
               continue

           members1 = set([square])
           changed = True
           while changed:
               changed = False
               for member in members1.copy():
                   for neighbour in member.neighbours:
                       if neighbour.color == square.color and neighbour not in members1:
                           changed = True
                           members1.add(neighbour)
           ledges1 = 0
           for member in members1:
               for neighbour in member.neighbours:
                   if neighbour.color == EMPTY:
                       ledges1 += 1

           root = square.find()

           #print 'members1', square, root, members1
           #print 'ledges1', square, ledges1

           members2 = set()
           for square2 in self.squares:
               if square2.color != EMPTY and square2.find() == root:
                   members2.add(square2)

           ledges2 = root.ledges
           #print 'members2', square, root, members1
           #print 'ledges2', square, ledges2

           assert members1 == members2
           assert ledges1 == ledges2, ('ledges differ at %r: %d %d' % (square, ledges1, ledges2))

           empties1 = set(self.emptyset.empties)

           empties2 = set()
           for square in self.squares:
               if square.color == EMPTY:
                   empties2.add(square.pos)

    def __repr__(self):
        result = []
        for y in range(SIZE):
            start = to_pos(0, y)
            result.append(''.join([SHOW[square.color]+' ' for square in self.squares[start:start+SIZE]]))
        return '\n'.join(result)

class UCTNode:
    def __init__(self):
        self.bestchild = None
        self.pos = -1
        self.wins = 0
        self.losses = 0
        self.pos_child = [None for x in range(SIZE*SIZE)]
        self.parent = None

    def play(self, board):
        """ uct tree search """
        color = board.color
        node = self
        path = [node]
        while True:
            pos = node.select(board)
            if pos == PASS:
                break
            board.move(pos)
            child = node.pos_child[pos]
            if not child:
                child = node.pos_child[pos] = UCTNode()
                child.unexplored = board.useful_moves()
                child.pos = pos
                child.parent = node
                path.append(child)
                break
            path.append(child)
            node = child
        self.random_playout(board)
        self.update_path(board, color, path)

    def select(self, board):
        """ select move; unexplored children first, then according to uct value """
        if self.unexplored:
            i = random.randrange(len(self.unexplored))
            pos = self.unexplored[i]
            self.unexplored[i] = self.unexplored[len(self.unexplored)-1]
            self.unexplored.pop()
            return pos
        elif self.bestchild:
            return self.bestchild.pos
        else:
            return PASS

    def random_playout(self, board):
        """ random play until both players pass """
        for x in range(MAXMOVES): # XXX while not self.finished?
            if board.finished:
                break
            board.move(board.random_move())

    def update_path(self, board, color, path):
        """ update win/loss count along path """
        wins = board.score(BLACK) >= board.score(WHITE)
        for node in path:
            if color == BLACK: color = WHITE
            else: color = BLACK
            if wins == (color == BLACK):
                node.wins += 1
            else:
                node.losses += 1
            if node.parent:
                node.parent.bestchild = node.parent.best_child()

    def score(self):
        winrate = self.wins/float(self.wins+self.losses)
        parentvisits = self.parent.wins+self.parent.losses
        if not parentvisits:
            return winrate
        nodevisits = self.wins+self.losses
        return winrate + math.sqrt((math.log(parentvisits))/(5*nodevisits))

    def best_child(self):
        maxscore = -1
        maxchild = None
        for child in self.pos_child:
            if child and child.score() > maxscore:
                maxchild = child
                maxscore = child.score()
        return maxchild

    def best_visited(self):
        maxvisits = -1
        maxchild = None
        for child in self.pos_child:
#            if child:
#                print to_xy(child.pos), child.wins, child.losses, child.score()
            if child and (child.wins+child.losses) > maxvisits:
                maxvisits, maxchild = (child.wins+child.losses), child
        return maxchild

def user_move(board):
    while True:
        text = raw_input('?').strip()
        if text == 'p':
            return PASS
        if text == 'q':
            raise EOFError
        try:
            x, y = [int(i) for i in text.split()]
        except ValueError:
            continue
        if not (0 <= x < SIZE and 0 <= y < SIZE):
            continue
        pos = to_pos(x, y)
        if board.useful(pos):
            return pos

def computer_move(board):
    global MOVES
    pos = board.random_move()
    if pos == PASS:
        return PASS
    tree = UCTNode()
    tree.unexplored = board.useful_moves()
    nboard = Board()
    for game in range(GAMES):
        node = tree
        nboard.reset()
        nboard.replay(board.history)
        node.play(nboard)
#    print 'moves', MOVES
    return tree.best_visited().pos

def versus_cpu():
    random.seed(1)
    board = Board()
    pos = computer_move(board)

def main(n):
    times = []
    for i in range(5):
        versus_cpu() # warmup
    for i in range(n):
        t1 = time.time()
        versus_cpu()
        t2 = time.time()
        times.append(t2 - t1)
    return times

if __name__ == "__main__":
    import util, optparse
    parser = optparse.OptionParser(
        usage="%prog [options]",
        description="Test the performance of the Go benchmark")
    util.add_standard_options_to(parser)
    options, args = parser.parse_args()

    util.run_benchmark(options, options.num_runs, main)


text:
author: Jeff Van Campen
comments: true
date: 2010-09-26 21:51:15+00:00
layout: post
slug: the-glittering-world-of-the-salons
title: The glittering world of the salons
wordpress_id: 756
category: notes
tags:
- age of enlightenment
- collaboration
- ideas
- meetups
- salons
- Steven Johnson
- video
---

> Oftentimes, the thing that turns a hunch into a real breakthrough is another hunch that's lurking in somebody else's mind. And you have to figure out a way to create systems that allow those hunches to come together and turn into something bigger than the sum of their parts. That's why, for instance, the coffee houses of the Age of Enlightenment and the Parisian salons of Modernism were such engines of creativity: because the created a space where ideas could mingle, swap and create new forms.

Steven Johnson discusses [where good ideas come from](http://www.youtube.com/watch?v=NugRZGDbPFU). I was struck by the notion that in order for ideas to come to fruition, they need to encounter other half-formed ideas.  He mentions the coffee houses and salon of the past, but it occurred to me that we have much the same thing today. Every week in London, there's are a seemingly endless stream of meetups and events. In my case, the ones I attend regularly are [London IA](http://london-ia.ning.com/), [UX Bookclub London](http://www.meetup.com/uxbcldn/), [UK UPA events](http://www.ukupa.org.uk/), [London Web Standards](http://www.londonwebstandards.org/) (which I've also helped organize), and [London Web](http://www.meetup.com/londonweb/), amongst others. Not to mention the many conferences and unconferences that take place over the course of the year.

Most of these feature somebody speaking about a topic of interest, which is a great way to learn about something new. But Steven Johnson's talk has made me realize what I really get out of these events: they allow me to talk people who are interested in the same things as I am. These are the people that help me clarify my ideas, and in some cases, help me make them happen.

[youtube http://www.youtube.com/watch?v=NugRZGDbPFU&hl=en_GB&fs=1&rel=0]


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Account extends CI_Controller {
  public $data;
  function __construct()
  {
    parent::__construct();

    session_start();
    session_write_close();

    require_once 'output_message.php';
    $output_message = new Output_Message();

    if ( !empty($_SESSION['is_logged_in']) AND $_SESSION['is_logged_in'] == 1 ) {
      $this->load->model('account_model');
      $this->load->model('telco_model');
      $this->load->model('bank_request_model');

      $this->data["page_title"] = "TOPUP";
      $this->data["page_header"] = $this->uri->segment(1);
      $this->data["page_action"] = $this->uri->segment(2);

      $this->data['current_id']       = $_SESSION['current_id'];
      $this->data['current_name']     = $_SESSION['current_name'];
      $this->data['current_group_id'] = $_SESSION['current_group_id'];

      // Count pending downline bank-in request
      $this->data['downline_pending_requests'] = $this->bank_request_model->count_pending_downline_requests($this->data['current_id']);

      // Restrict Access is not Admin or Direct upline
      if ($this->data['current_group_id'] != 1 && $this->uri->segment(3)) {
        $account_id = $this->uri->segment(3);
        $account = $this->account_model->get_account($account_id);
        if ($account->upline_id != $this->data['current_id']) {
          die('ACCESS DENIED');
        }
      }

      if (!empty($_SESSION['form_data'])) {
        $this->data['form_data'] = $_SESSION['form_data'];
        session_start();
        $_SESSION['form_data']   = null;
        session_write_close();
      }

      if (!empty($_SESSION['status_code']) AND !empty($_SESSION['status_message'])) {
        $status_code             = $_SESSION['status_code'];
        $status_message          = $_SESSION['status_message'];
        $this->data['output_status_message'] = $output_message->get_success_error_message($status_code, $status_message);
        session_start();
        $_SESSION['status_code']    = null;
        $_SESSION['status_message'] = null;
        session_write_close();
      }
    } else {
      redirect('/login/index');
    }
  }// End __construct

  function dd($data) {
      echo "
";
      print_r($data);
      echo "
";
  }// End dd

  function index() {
    $this->data["all_accounts"] = $this->account_model->get_all_accounts($this->data['current_id']);

    $this->load->view('templates/main_header', $this->data);
    $this->load->view('account/index', $this->data);
    $this->load->view('templates/main_footer', $this->data);
  }// End index

  function create() {
    $upline = $this->account_model->get_account_balance($this->data['current_id']);

    if (!empty($this->data['form_data'])) {
      foreach($this->data['form_data'] as $key => $value) {
          $this->data[$key] = $value;
      }
    }

    // Only available to admin, master and dealer
    switch ($this->data['current_group_id']) {
      case 'admin':
        $this->data['level'] = array(""=> "Select One", "master"=>"Master", "dealer"=>"Dealer", "agent"=>"Agent");
        $this->data['max_balance'] = "50000";//$upline->balance;//"100000";
        break;
      case 'master':
        $this->data['level'] = array(""=> "Select One", "dealer"=>"Dealer", "agent"=>"Agent");
        $this->data['max_balance'] = $upline->balance;
        break;

      default:
        $this->data['level'] = array(""=> "Select One", "agent"=>"Agent");
        $this->data['max_balance'] = $upline->balance;
        break;
    }

    $this->load->view('templates/main_header', $this->data);
    $this->load->view('account/create', $this->data);
    $this->load->view('templates/main_footer', $this->data);
  }// End create

  function store() {
    $this->form_validation->set_rules('current_id', 'Current Id', 'required|trim|xss_clean');
    $this->form_validation->set_rules('current_name', 'Current Name', 'required|trim|xss_clean');
    $this->form_validation->set_rules('current_group_id', 'Current Group Id', 'required|trim|xss_clean');
    $this->form_validation->set_rules('group_id', 'Level', 'required|trim|xss_clean');
    $this->form_validation->set_rules('name', 'Name', 'required|trim|xss_clean');
    $this->form_validation->set_rules('phone_number', 'Phone Number', 'required|trim|xss_clean');
    $this->form_validation->set_rules('open', 'Opening Balance', 'required|trim|xss_clean');

    if ($this->form_validation->run()) {
      $insert_query = $this->account_model->store();
      if($insert_query[0])
      {
        $open = $this->input->post("open");
        $phone_number = $this->input->post("phone_number");
        $password = $insert_query[2];// return random generated password from model
        require_once 'my_twilio.php';
        $my_twilio = new My_Twilio();
        $to = "{$phone_number}";
        $body = "Login ID:{$phone_number} Password:{$password} Balance:{$open} Address:". base_url();
        $my_twilio->send_sms($to, $body);

        $account_id = $insert_query[1];

        $return_data = array(
                  "status"     => "success",
                  "message"    => "New account is successfully created.",
                  "account_id" => $account_id,
                  );
        echo json_encode($return_data);
      }
      else
      {
        // echo validation_errors();
        $return_data = array(
                  "status" => "failed",
                  "message" => "Failed to new account. Please try again.",
                  );
        echo json_encode($return_data);
      }
    } else {
      // echo validation_errors();
      $return_data = array(
                "status" => "failed",
                "message" => "Form Validation failed. Please try again.",
                );
      echo json_encode($return_data);
    }
  }// End store

  function redirect_to_show() {
    $status = $this->input->get('status', true);
    $message = $this->input->get('message', true);
    $account_id = $this->input->get('account_id', true);

    if($status == "success") {
      session_start();
      $_SESSION['status_code'] = 1;
      $_SESSION['status_message'] = $message;
      session_write_close();
      redirect("/account/show/{$account_id}");
    } else {
      session_start();
      $_SESSION['status_code'] = 9;
      $_SESSION['status_message'] = $message;
      session_write_close();
      redirect("/account/create");
    }
  }// End redirect_to_show

  function show() {
    $id = $this->uri->segment(3);
    $this->data["account"] = $this->account_model->get_account($id);

    // Check and get existing account tax
    $account_tax = $this->account_model->get_account_tax($id, false);

    // Get Upline Tax
    // If admin, get from tax table directly
    $upline_tax = $this->account_model->get_upline_tax_rate($this->data['account']->upline_id);

    // Organize the $upline_tax array in asc order
    function compareItems($a, $b) {
      if ( $a->telco_id < $b->telco_id ) return -1;
      if ( $a->telco_id > $b->telco_id ) return 1;
      return 0; // equality
    }
    if ($this->data['current_group_id'] != 1) {
        uasort($upline_tax, "compareItems");
    }

    // Setup $tax_data from $account_tax
    $tax_data = array();
    if(!empty($account_tax)) {
      foreach($account_tax as $key) {
        $tax_data[$key->telco_id]["id"]       = $key->telco_id;
        $tax_data[$key->telco_id]["name"]     = "";
        $tax_data[$key->telco_id]["status"]   = (empty($key->status) ? 'false' : 'true');
        $tax_data[$key->telco_id]["rate"]     = $key->rate;
        $tax_data[$key->telco_id]["max_rate"] = 0;
      }
    }

    // Check if any new telco and tax added into the system
    if (!empty($upline_tax)) {
      foreach($upline_tax as $up) {
          if(array_key_exists($up->telco_id, $tax_data))
          {
            $tax_data[$up->telco_id]["name"]     = $up->telco_name;
            $tax_data[$up->telco_id]["max_rate"] = $up->rate;
          }
          else
          {
            $tax_data[$up->telco_id]["id"]       = $up->telco_id;
            $tax_data[$up->telco_id]["name"]     = $up->telco_name;
            $tax_data[$up->telco_id]["status"]   = 'false';
            $tax_data[$up->telco_id]["rate"]     = 0;
            $tax_data[$up->telco_id]["max_rate"] = $up->rate;
          }
      }
    }
    $this->data["tax_data"] = $tax_data;

    $this->load->view('templates/main_header', $this->data);
    $this->load->view('account/show', $this->data);
    $this->load->view('templates/main_footer', $this->data);
  }// End show

  function edit() {
    $id = $this->uri->segment(3);
    $this->data["account"] = $this->account_model->get_account($id);

    $upline = $this->account_model->get_account_balance($this->data['current_id']);

    if ($this->data['current_group_id'] == 1) {
      $this->data['level'] = array(""=> "Select One", "master"=>"Master", "dealer"=>"dealer", "agent"=>"agent");
      $this->data['max_balance'] = $upline->balance;//"100000";
    } else if($this->data['current_group_id'] == 2) {
      $this->data['level'] = array(""=> "Select One", "dealer"=>"dealer", "agent"=>"agent");
      $this->data['max_balance'] = $upline->balance;
    } else {
      $this->data['level'] = array(""=> "Select One", "agent"=>"agent");
      $this->data['max_balance'] = $upline->balance;
    }

    $this->load->view('templates/main_header', $this->data);
    $this->load->view('account/edit', $this->data);
    $this->load->view('templates/main_footer', $this->data);
  }// End edit

  function update() {
    $this->form_validation->set_rules('current_id', 'Current Id', 'required|trim|xss_clean');
    $this->form_validation->set_rules('current_name', 'Current Name', 'required|trim|xss_clean');
    $this->form_validation->set_rules('current_group_id', 'Current Group Id', 'required|trim|xss_clean');
    $this->form_validation->set_rules('account_id', 'account Id', 'required|trim|xss_clean');
    $this->form_validation->set_rules('group_id', 'Level', 'required|trim|xss_clean');
    $this->form_validation->set_rules('name', 'Name', 'required|trim|xss_clean');
    $this->form_validation->set_rules('phone_number', 'Phone Number', 'required|trim|xss_clean');

    if ($this->form_validation->run()) {
      $update_query = $this->account_model->update();
      if($update_query)
      {
        session_start();
        $_SESSION['status_code'] = 1;
        $_SESSION['status_message'] = "account is successfully updated.";
        session_write_close();
        redirect("/account/index");
      }
      else
      {
        session_start();
        $_SESSION['form_data'] = $form_data = null;
        $_SESSION['status_code'] = 9;
        $_SESSION['status_message'] = "Failed to update account. Please try again.";
        session_write_close();
        $id = $this->input->post('id');
        redirect("/account/edit/{$id}");
      }
    } else {
      session_start();
      $_SESSION['form_data'] = $form_data = null;
      $_SESSION['status_code'] = 9;
      $_SESSION['status_message'] = "Form Validation Failed. Please try again.";
      session_write_close();
      $id = $this->input->post('id');
      redirect("/account/edit/{$id}");
    }
  }// End update

  function reset_password() {
    $this->form_validation->set_rules('id', 'Account Id', 'required|trim|xss_clean');
    $upline_id    = $this->data['current_id'];
    $current_name = $this->data['current_name'];

    if($this->form_validation->run()) {
      $query = $this->account_model->reset_password($upline_id, $current_name);
      if($query[0]) {
        $phone_number = $query[1];
        $password     = $query[2];// return random generated password from model
        require_once 'my_twilio.php';
        $my_twilio = new My_Twilio();
        $to        = "{$phone_number}";
        $body      = "Password Reset. Login ID:{$phone_number} Password:{$password} Address: ".base_url();
        $my_twilio->send_sms($to, $body);

        $return_data = array(
                  "status"  => "success",
                  "message" => "Downline Password is successfully reset.",
                  );
        echo json_encode($return_data);
      } else {
        // echo validation_errors();
        $return_data = array(
                  "status"  => "failed",
                  "message" => "Failed to reset account password. Please try again.",
                  );
        echo json_encode($return_data);
      }
    } else {
      // echo validation_errors();
      $return_data = array(
                "status"  => "failed",
                "message" => "Form Validation failed. Please try again.",
                );
      echo json_encode($return_data);
    }
  }// End reset_password

  function redirect_to_index() {
    $status = $this->input->get('status', true);
    $message = $this->input->get('message', true);

    if($status == "success") {
      session_start();
      $_SESSION['status_code'] = 1;
      $_SESSION['status_message'] = $message;
      session_write_close();
    } else {
      session_start();
      $_SESSION['status_code'] = 9;
      $_SESSION['status_message'] = $message;
      session_write_close();
    }
    redirect('/account/index');
  }// End redirect_to_index

  function update_account_tax() {
    $this->form_validation->set_rules('current_name', 'Current Name', 'required|trim|xss_clean');
    $this->form_validation->set_rules('account_id', 'account Id', 'required|trim|xss_clean');
    $this->form_validation->set_rules('upline_id', 'Upline Id', 'required|trim|xss_clean');
    // Get the field_name and validate
    $rate_field = $this->input->post('rate_field');
    foreach($rate_field as $key) {
        $this->form_validation->set_rules($key, 'Rate Field', 'required|trim|xss_clean');
    }

    if ($this->form_validation->run()) {
      $insert_query = $this->account_model->update_account_tax();
      if($insert_query)
      {
        session_start();
        $_SESSION['status_code'] = 1;
        $_SESSION['status_message'] = "account is successfully updated.";
        session_write_close();
        redirect("/account/index");
      }
      else
      {
        session_start();
        $_SESSION['form_data'] = $form_data = null;
        $_SESSION['status_code'] = 9;
        $_SESSION['status_message'] = "Failed to update account. Please try again.";
        session_write_close();
        $account_id = $this->input->post('account_id');
        redirect("/account/show/{$account_id}");
      }
    } else {
      // echo validation_errors();
      session_start();
      $_SESSION['form_data'] = $form_data = null;
      $_SESSION['status_code'] = 9;
      $_SESSION['status_message'] = "Form Validation Failed. Please try again.";
      session_write_close();
      $account_id = $this->input->post('account_id');
      redirect("/account/show/{$account_id}");
    }
  }// End update_account_tax

  function destroy() {
    $id = $this->input->get_post('id');
    $delete_query = $this->account_model->destory($id, $this->data['current_name']);
    if($delete_query)
    {
      session_start();
      $_SESSION['status_code'] = 1;
      $_SESSION['status_message'] = "account is successfully deleted.";
      session_write_close();
      redirect("/account/index");
    }
    else
    {
      session_start();
      $_SESSION['form_data'] = $form_data;
      $_SESSION['status_code'] = 9;
      $_SESSION['status_message'] = "Failed to delete account. Please try again.";
      session_write_close();
      redirect("/account/index");
    }
  }// End destroy

  function show_account_tax_history() {
    $id = $this->uri->segment(3);
    $this->data['account_id'] = $id;
    $this->data["account_tax_history"] = $this->account_model->get_account_tax($id, true);

    $this->load->view('templates/main_header', $this->data);
    $this->load->view('account/show_account_tax_history', $this->data);
    $this->load->view('templates/main_footer', $this->data);
  }// End show_account_tax_history

  function check_phone_number_availability() {
    $phone_number = $_POST['phone_number'];
    $account_id = ( isset($_POST['account_id']) ? $_POST['account_id'] : null);

    if(!is_null($account_id)) {
        $account = $this->account_model->get_account($account_id);
        if ($account->phone_number == $phone_number) {
          $this->output->set_content_type('application/json')->set_output(json_encode(array('valid'=>true)));
          return;
        }
    }

    $query = $this->account_model->check_phone_number_availability($phone_number, $account_id);

    if ($query === false) {
      $this->output->set_content_type('application/json')->set_output(json_encode(array('valid'=>false)));
    } else {
      $this->output->set_content_type('application/json')->set_output(json_encode(array('valid'=>true)));
    }
  }// End check_phone_number_availability
}// End Account


text:
class SettingDefaultOrderToItems < ActiveRecord::Migration
  def up
    Item.all.each do |item|
      item.order = 0
      item.save
    end
  end

  def down
  end
end


text:
using System;
using Overflow.Behaviors;
using Overflow.Test.Fakes;
using Overflow.Test.TestingInfrastructure;
using Xunit;

namespace Overflow.Test.Behaviors
{
    public class OperationBehaviorAttributeFactoryTests
    {
        [Theory, AutoMoqData]
        public void Behaviors_are_created_for_the_available_behavior_attributes(WorkflowConfiguration configuration, BehaviorOperation operation)
        {
            var sut = new OperationBehaviorAttributeFactory();

            var result = sut.CreateBehaviors(operation, configuration);

            Assert.Equal(1, result.Count);
            Assert.IsType<FakeOperationBehavior>(result[0]);
        }

        [Theory, AutoMoqData]
        public void No_behaviors_are_created_when_there_are_no_behavior_attributes(WorkflowConfiguration configuration, IOperation operation)
        {
            var sut = new OperationBehaviorAttributeFactory();

            var result = sut.CreateBehaviors(operation, configuration);

            Assert.Equal(0, result.Count);
        }

        [Theory, AutoMoqData]
        public void You_cannot_create_behaviors_without_an_operation(WorkflowConfiguration configuration)
        {
            var sut = new OperationBehaviorAttributeFactory();

            Assert.Throws<ArgumentNullException>(() => sut.CreateBehaviors(null, configuration));
        }

        [Theory, AutoMoqData]
        public void Behaviors_are_created_with_the_workflow_configuration(WorkflowConfiguration configuration, BehaviorOperation operation)
        {
            var sut = new OperationBehaviorAttributeFactory();

            var result = (FakeOperationBehavior)sut.CreateBehaviors(operation, configuration)[0];

            Assert.Equal(configuration, result.Configuration);
        }

        [FakeOperationBehavior]
        public class BehaviorOperation : Operation { }
    }
}


text:
namespace Platformer.Engine
{
    using System;
    using Services;

    /// <summary>
    /// Interface implemented by the main game engine.
    /// </summary>
    public interface IGameEngine
    {
        /// <summary>
        /// Gets a value indicating whether the game is currently running.
        /// </summary>
        bool IsRunning { get; }

        /// <summary>
        /// Gets the currently loaded map.
        /// </summary>
        Map CurrentMap { get; }

        /// <summary>
        /// Gets the amount of time the game has been running, in seconds.
        /// </summary>
        double GlobalTime { get; }

        /// <summary>
        /// Gets the amount of time between the last two frames.
        /// </summary>
        double DeltaTime { get; }

        /// <summary>
        /// Gets or sets a value indicating whether the game engine is paused.
        /// </summary>
        /// <value>
        ///   <c>true</c> if paused; otherwise, <c>false</c>.
        /// </value>
        bool Paused { get; set; }

        /// <summary>
        /// Gets a game service.
        /// </summary>
        /// <typeparam name="TService">The type of the service to obtain.</typeparam>
        /// <returns>An instance of a game service.</returns>
        TService GetService<TService>() where TService : IGameService;

        /// <summary>
        /// Loads and starts a game level.
        /// </summary>
        /// <param name="levelPath">The level path.</param>
        void StartLevel(string levelPath);

        /// <summary>
        /// Called each frame to run the game logic.
        /// </summary>
        /// <param name="singleStep">If true, does not perform any FPS rate control and simply increments time by a single predefined time step.</param>
        void Step(bool singleStep);

        /// <summary>
        /// Stops the level.
        /// </summary>
        void StopLevel();
    }
}


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Monkey HTTP Server
 *  ==================
 *  Copyright 2001-2016 Monkey Software LLC <eduardo@monkey.io>
 *
 *  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.
 */

#ifndef MK_NET_H
#define MK_NET_H

#include <monkey/mk_core.h>
#include <monkey/mk_stream.h>

struct mk_net_connection {
    struct mk_event event;
    int fd;
    char *host;
    int port;
    void *thread;
};

struct mk_net_connection *mk_net_conn_create(char *addr, int port);
int mk_net_conn_write(struct mk_channel *channel,
                      void *data, size_t len);

#endif