text:
package org.joverseer.ui.support.transferHandlers;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

/**
 * A generic transfer handler for exporting data via dnd from a component
 * Users must implement the createTransferable method to provide the transferable
 *
 * @author Marios Skounakis
 */
@SuppressWarnings("serial")
public abstract class GenericExportTransferHandler extends TransferHandler {

    @Override
	public boolean canImport(JComponent arg0, DataFlavor[] arg1) {
        return false;
    }

    @Override
	public int getSourceActions(JComponent c) {
        return COPY_OR_MOVE;
    }

    @Override
	protected void exportDone(JComponent c, Transferable data, int action) {
    }

    @Override
	protected abstract Transferable createTransferable(JComponent arg0);

}


text:
var access = function (profile, users, models, logWriter) {
    var getAccess = function (req, uId, mid, callback) {
        models.get(req.session.lastDb - 1, 'Users', users.schema).findById(uId, function (err, user) {
            if (user) {
                models.get(req.session.lastDb - 1, 'Profile', profile).aggregate(
                {
                    $project: {
                        profileAccess: 1
                    }
                },
                {
                    $match: {
                        _id: user.profile
                    }
                },
                {
                    $unwind: "$profileAccess"
                },

                {
                    $match: {
                        'profileAccess.module': mid
                    }
                },

                function (err, result) {
                    return callback({ error: err, result: result })
                }
            );
            } else {
                logWriter.log('access.js users.findById error' + err);
                res.send(500, { error: 'access.js users.findById error' });
            }
        });
    };

    var getReadAccess = function (req, uId, mid, callback) {
        getAccess(req, uId, mid, function (res) {
            if (res.error) {
                console.log(res.error);
            } else {
                callback(res.result[0].profileAccess.access.read);
            }
        });
    };
    var getEditWritAccess = function (req, uId, mid, callback) {
        getAccess(req, uId, mid, function (res) {
            if (res.error) {
                console.log(res.error);
            } else {
                callback(res.result[0].profileAccess.access.editWrite);
            }
        });

    };
    var getDeleteAccess = function (req, uId, mid, callback) {
        getAccess(req, uId, mid, function (res) {
            if (res.error) {
                console.log(res.error);
            } else {
                callback(res.result[0].profileAccess.access.del);
            }
        });
    };

    return {
        getReadAccess: getReadAccess,
        getEditWritAccess: getEditWritAccess,
        getDeleteAccess: getDeleteAccess
    }
};
module.exports = access;

redpajama_set_name: RedPajamaGithub


text:
.navigation-bar .item.divider {
    width: 1px;

    background-image: linear-gradient(hsl(0, 0%, 74%), hsl(0, 0%, 74%));
    background-size: 100% 16px;
    background-repeat: no-repeat;
    background-position: center;
}

@media (-webkit-min-device-pixel-ratio: 2) {
    .navigation-bar .item.divider {
        width: 0.5px;
    }
}


text:
sap.ui.define(['./SemanticButton'], function(SemanticButton) {
	"use strict";

	/**
	* Constructor for a new MessagesIndicator.
	* @param {string} [sId] ID for the new control, generated automatically if no ID is given
	* @param {object} [mSettings] Optional initial settings for the new control:  a map/JSON-object with initial property values, event listeners etc. for the new object
	*
	* @class
	* A semantic-specific button, eligible for the messagesIndicator aggregation of the
	* {@link sap.f.semantic.SemanticPage} to be placed in its footer.
	*
	* @extends sap.f.semantic.SemanticButton
	*
	* @author SAP SE
	* @version ${version}
	*
	* @constructor
	* @public
	* @since 1.46.0
	* @alias sap.f.semantic.MessagesIndicator
	*/
	var MessagesIndicator = SemanticButton.extend("sap.f.semantic.MessagesIndicator", /** @lends sap.f.semantic.MessagesIndicator.prototype */ {
		metadata: {
			library: "sap.f"
		}
	});

	return MessagesIndicator;
});


text:
/*
struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
            label(x), next(NULL), random(NULL) {
    }
};
*/
class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
	{
		if (pHead == NULL)
		{
			return NULL;
		}
		RandomListNode* pHeadTemp = pHead;
		while (pHeadTemp)
		{
			RandomListNode* pNodeClone = new RandomListNode(pHeadTemp->label);
			RandomListNode* pNodeTemp = pHeadTemp->next;
			pHeadTemp->next = pNodeClone;
			pNodeClone->next = pNodeTemp;
			pHeadTemp = pNodeTemp;
		}

		pHeadTemp = pHead;

		while (pHeadTemp)
		{

			if (pHeadTemp->random)
			{
				pHeadTemp->next->random = pHeadTemp->random->next;
			}

			pHeadTemp = pHeadTemp->next->next;
		}

		pHeadTemp = pHead;
		RandomListNode* result = pHead->next;
		RandomListNode* resultTemp = pHead->next;

		while (pHeadTemp)
		{
			pHeadTemp->next = resultTemp->next;
			if (resultTemp->next == NULL)
			{
				break;
			}
			else
			{
				resultTemp->next = resultTemp->next->next;
			}
			pHeadTemp = pHeadTemp->next;
			resultTemp = pHeadTemp->next;
		}

		return result;

		  //拆分
        // RandomListNode *pCloneHead = pHead->next;
        // RandomListNode *tmp;
        // RandomListNode *currNode = pHead;
        // while(currNode->next){
        //     tmp = currNode->next;
        //     currNode->next =tmp->next;
        //     currNode = tmp;
        // }
        // return pCloneHead;
	}

};


text:
@class AXStretchableHeaderView;

@protocol AXStretchableHeaderViewDelegate <NSObject>
- (NSArray *)interactiveSubviewsInStretchableHeaderView:(AXStretchableHeaderView *)stretchableHeaderView;
@end

@interface AXStretchableHeaderView : UIView
@property (nonatomic) id<AXStretchableHeaderViewDelegate> delegate;
@property (nonatomic) CGFloat minimumOfHeight;
@property (nonatomic) CGFloat maximumOfHeight;
@property (nonatomic) BOOL bounces;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;
@end


text:
/*===- InstrProfilingValue.c - Support library for PGO instrumentation ----===*\
|*
|*                     The LLVM Compiler Infrastructure
|*
|* This file is distributed under the University of Illinois Open Source
|* License. See LICENSE.TXT for details.
|*
\*===----------------------------------------------------------------------===*/

#include "InstrProfiling.h"
#include "InstrProfilingInternal.h"
#include "InstrProfilingUtil.h" /* For PS4 getenv shim. */
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INSTR_PROF_VALUE_PROF_DATA
#define INSTR_PROF_COMMON_API_IMPL
#include "InstrProfData.inc"

static int hasStaticCounters = 1;
static int OutOfNodesWarnings = 0;
static int hasNonDefaultValsPerSite = 0;
#define INSTR_PROF_MAX_VP_WARNS 10
#define INSTR_PROF_DEFAULT_NUM_VAL_PER_SITE 8
#define INSTR_PROF_VNODE_POOL_SIZE 1024

#ifndef _MSC_VER
/* A shared static pool in addition to the vnodes statically
 * allocated by the compiler.  */
COMPILER_RT_VISIBILITY ValueProfNode
    lprofValueProfNodes[INSTR_PROF_VNODE_POOL_SIZE] COMPILER_RT_SECTION(
       COMPILER_RT_SEG INSTR_PROF_VNODES_SECT_NAME_STR);
#endif

COMPILER_RT_VISIBILITY uint32_t VPMaxNumValsPerSite =
    INSTR_PROF_DEFAULT_NUM_VAL_PER_SITE;

COMPILER_RT_VISIBILITY void lprofSetupValueProfiler() {
  const char *Str = 0;
  Str = getenv("LLVM_VP_MAX_NUM_VALS_PER_SITE");
  if (Str && Str[0]) {
    VPMaxNumValsPerSite = atoi(Str);
    hasNonDefaultValsPerSite = 1;
  }
  if (VPMaxNumValsPerSite > INSTR_PROF_MAX_NUM_VAL_PER_SITE)
    VPMaxNumValsPerSite = INSTR_PROF_MAX_NUM_VAL_PER_SITE;
}

COMPILER_RT_VISIBILITY void lprofSetMaxValsPerSite(uint32_t MaxVals) {
  VPMaxNumValsPerSite = MaxVals;
  hasNonDefaultValsPerSite = 1;
}

/* This method is only used in value profiler mock testing.  */
COMPILER_RT_VISIBILITY void
__llvm_profile_set_num_value_sites(__llvm_profile_data *Data,
                                   uint32_t ValueKind, uint16_t NumValueSites) {
  *((uint16_t *)&Data->NumValueSites[ValueKind]) = NumValueSites;
}

/* This method is only used in value profiler mock testing.  */
COMPILER_RT_VISIBILITY const __llvm_profile_data *
__llvm_profile_iterate_data(const __llvm_profile_data *Data) {
  return Data + 1;
}

/* This method is only used in value profiler mock testing.  */
COMPILER_RT_VISIBILITY void *
__llvm_get_function_addr(const __llvm_profile_data *Data) {
  return Data->FunctionPointer;
}

/* Allocate an array that holds the pointers to the linked lists of
 * value profile counter nodes. The number of element of the array
 * is the total number of value profile sites instrumented. Returns
 * 0 if allocation fails.
 */

static int allocateValueProfileCounters(__llvm_profile_data *Data) {
  uint64_t NumVSites = 0;
  uint32_t VKI;

  /* This function will never be called when value site array is allocated
     statically at compile time.  */
  hasStaticCounters = 0;
  /* When dynamic allocation is enabled, allow tracking the max number of
   * values allowd.  */
  if (!hasNonDefaultValsPerSite)
    VPMaxNumValsPerSite = INSTR_PROF_MAX_NUM_VAL_PER_SITE;

  for (VKI = IPVK_First; VKI <= IPVK_Last; ++VKI)
    NumVSites += Data->NumValueSites[VKI];

  ValueProfNode **Mem =
      (ValueProfNode **)calloc(NumVSites, sizeof(ValueProfNode *));
  if (!Mem)
    return 0;
  if (!COMPILER_RT_BOOL_CMPXCHG(&Data->Values, 0, Mem)) {
    free(Mem);
    return 0;
  }
  return 1;
}

static ValueProfNode *allocateOneNode(__llvm_profile_data *Data, uint32_t Index,
                                      uint64_t Value) {
  ValueProfNode *Node;

  if (!hasStaticCounters)
    return (ValueProfNode *)calloc(1, sizeof(ValueProfNode));

  /* Early check to avoid value wrapping around.  */
  if (CurrentVNode + 1 > EndVNode) {
    if (OutOfNodesWarnings++ < INSTR_PROF_MAX_VP_WARNS) {
      PROF_WARN("Unable to track new values: %s. "
                " Consider using option -mllvm -vp-counters-per-site=<n> to "
                "allocate more"
                " value profile counters at compile time. \n",
                "Running out of static counters");
    }
    return 0;
  }
  Node = COMPILER_RT_PTR_FETCH_ADD(ValueProfNode, CurrentVNode, 1);
  /* Due to section padding, EndVNode point to a byte which is one pass
   * an incomplete VNode, so we need to skip the last incomplete node. */
  if (Node + 1 > EndVNode)
    return 0;

  return Node;
}

COMPILER_RT_VISIBILITY void
__llvm_profile_instrument_target(uint64_t TargetValue, void *Data,
                                 uint32_t CounterIndex) {
  __llvm_profile_data *PData = (__llvm_profile_data *)Data;
  if (!PData)
    return;

  if (!PData->Values) {
    if (!allocateValueProfileCounters(PData))
      return;
  }

  ValueProfNode **ValueCounters = (ValueProfNode **)PData->Values;
  ValueProfNode *PrevVNode = NULL;
  ValueProfNode *MinCountVNode = NULL;
  ValueProfNode *CurVNode = ValueCounters[CounterIndex];
  uint64_t MinCount = UINT64_MAX;

  uint8_t VDataCount = 0;
  while (CurVNode) {
    if (TargetValue == CurVNode->Value) {
      CurVNode->Count++;
      return;
    }
    if (CurVNode->Count < MinCount) {
      MinCount = CurVNode->Count;
      MinCountVNode = CurVNode;
    }
    PrevVNode = CurVNode;
    CurVNode = CurVNode->Next;
    ++VDataCount;
  }

  if (VDataCount >= VPMaxNumValsPerSite) {
    /* Bump down the min count node's count. If it reaches 0,
     * evict it. This eviction/replacement policy makes hot
     * targets more sticky while cold targets less so. In other
     * words, it makes it less likely for the hot targets to be
     * prematurally evicted during warmup/establishment period,
     * when their counts are still low. In a special case when
     * the number of values tracked is reduced to only one, this
     * policy will guarantee that the dominating target with >50%
     * total count will survive in the end. Note that this scheme
     * allows the runtime to track the min count node in an adaptive
     * manner. It can correct previous mistakes and eventually
     * lock on a cold target that is alread in stable state.
     *
     * In very rare cases,  this replacement scheme may still lead
     * to target loss. For instance, out of \c N value slots, \c N-1
     * slots are occupied by luke warm targets during the warmup
     * period and the remaining one slot is competed by two or more
     * very hot targets. If those hot targets occur in an interleaved
     * way, none of them will survive (gain enough weight to throw out
     * other established entries) due to the ping-pong effect.
     * To handle this situation, user can choose to increase the max
     * number of tracked values per value site. Alternatively, a more
     * expensive eviction mechanism can be implemented. It requires
     * the runtime to track the total number of evictions per-site.
     * When the total number of evictions reaches certain threshold,
     * the runtime can wipe out more than one lowest count entries
     * to give space for hot targets.
     */
    if (!MinCountVNode->Count || !(--MinCountVNode->Count)) {
      CurVNode = MinCountVNode;
      CurVNode->Value = TargetValue;
      CurVNode->Count++;
    }
    return;
  }

  CurVNode = allocateOneNode(PData, CounterIndex, TargetValue);
  if (!CurVNode)
    return;
  CurVNode->Value = TargetValue;
  CurVNode->Count++;

  uint32_t Success = 0;
  if (!ValueCounters[CounterIndex])
    Success =
        COMPILER_RT_BOOL_CMPXCHG(&ValueCounters[CounterIndex], 0, CurVNode);
  else if (PrevVNode && !PrevVNode->Next)
    Success = COMPILER_RT_BOOL_CMPXCHG(&(PrevVNode->Next), 0, CurVNode);

  if (!Success && !hasStaticCounters) {
    free(CurVNode);
    return;
  }
}

/*
 * A wrapper struct that represents value profile runtime data.
 * Like InstrProfRecord class which is used by profiling host tools,
 * ValueProfRuntimeRecord also implements the abstract intefaces defined in
 * ValueProfRecordClosure so that the runtime data can be serialized using
 * shared C implementation.
 */
typedef struct ValueProfRuntimeRecord {
  const __llvm_profile_data *Data;
  ValueProfNode **NodesKind[IPVK_Last + 1];
  uint8_t **SiteCountArray;
} ValueProfRuntimeRecord;

/* ValueProfRecordClosure Interface implementation. */

static uint32_t getNumValueSitesRT(const void *R, uint32_t VK) {
  return ((const ValueProfRuntimeRecord *)R)->Data->NumValueSites[VK];
}

static uint32_t getNumValueDataRT(const void *R, uint32_t VK) {
  uint32_t S = 0, I;
  const ValueProfRuntimeRecord *Record = (const ValueProfRuntimeRecord *)R;
  if (Record->SiteCountArray[VK] == INSTR_PROF_NULLPTR)
    return 0;
  for (I = 0; I < Record->Data->NumValueSites[VK]; I++)
    S += Record->SiteCountArray[VK][I];
  return S;
}

static uint32_t getNumValueDataForSiteRT(const void *R, uint32_t VK,
                                         uint32_t S) {
  const ValueProfRuntimeRecord *Record = (const ValueProfRuntimeRecord *)R;
  return Record->SiteCountArray[VK][S];
}

static ValueProfRuntimeRecord RTRecord;
static ValueProfRecordClosure RTRecordClosure = {
    &RTRecord,          INSTR_PROF_NULLPTR, /* GetNumValueKinds */
    getNumValueSitesRT, getNumValueDataRT,  getNumValueDataForSiteRT,
    INSTR_PROF_NULLPTR, /* RemapValueData */
    INSTR_PROF_NULLPTR, /* GetValueForSite, */
    INSTR_PROF_NULLPTR  /* AllocValueProfData */
};

static uint32_t
initializeValueProfRuntimeRecord(const __llvm_profile_data *Data,
                                 uint8_t *SiteCountArray[]) {
  unsigned I, J, S = 0, NumValueKinds = 0;
  ValueProfNode **Nodes = (ValueProfNode **)Data->Values;
  RTRecord.Data = Data;
  RTRecord.SiteCountArray = SiteCountArray;
  for (I = 0; I <= IPVK_Last; I++) {
    uint16_t N = Data->NumValueSites[I];
    if (!N)
      continue;

    NumValueKinds++;

    RTRecord.NodesKind[I] = Nodes ? &Nodes[S] : INSTR_PROF_NULLPTR;
    for (J = 0; J < N; J++) {
      /* Compute value count for each site. */
      uint32_t C = 0;
      ValueProfNode *Site =
          Nodes ? RTRecord.NodesKind[I][J] : INSTR_PROF_NULLPTR;
      while (Site) {
        C++;
        Site = Site->Next;
      }
      if (C > UCHAR_MAX)
        C = UCHAR_MAX;
      RTRecord.SiteCountArray[I][J] = C;
    }
    S += N;
  }
  return NumValueKinds;
}

static ValueProfNode *getNextNValueData(uint32_t VK, uint32_t Site,
                                        InstrProfValueData *Dst,
                                        ValueProfNode *StartNode, uint32_t N) {
  unsigned I;
  ValueProfNode *VNode = StartNode ? StartNode : RTRecord.NodesKind[VK][Site];
  for (I = 0; I < N; I++) {
    Dst[I].Value = VNode->Value;
    Dst[I].Count = VNode->Count;
    VNode = VNode->Next;
  }
  return VNode;
}

static uint32_t getValueProfDataSizeWrapper(void) {
  return getValueProfDataSize(&RTRecordClosure);
}

static uint32_t getNumValueDataForSiteWrapper(uint32_t VK, uint32_t S) {
  return getNumValueDataForSiteRT(&RTRecord, VK, S);
}

static VPDataReaderType TheVPDataReader = {
    initializeValueProfRuntimeRecord, getValueProfRecordHeaderSize,
    getFirstValueProfRecord,          getNumValueDataForSiteWrapper,
    getValueProfDataSizeWrapper,      getNextNValueData};

COMPILER_RT_VISIBILITY VPDataReaderType *lprofGetVPDataReader() {
  return &TheVPDataReader;
}


text: run_spec(__dirname, ["babel", "flow", "typescript"]);


text:
__attribute__((visibility("hidden")))
@interface BRPopPanelControl : BRControl
{
}

- (void)layoutSubcontrols;

@end


text:
package org.jetbrains.plugins.github;

import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Clock;
import com.intellij.testFramework.VfsTestUtil;
import com.intellij.util.text.DateFormatUtil;
import git4idea.actions.GitInit;
import git4idea.commands.Git;
import git4idea.repo.GitRepository;
import git4idea.test.TestDialogHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.github.api.GithubFullPath;
import org.jetbrains.plugins.github.test.GithubTest;
import org.jetbrains.plugins.github.ui.GithubCreatePullRequestDialog;
import org.jetbrains.plugins.github.util.GithubUrlUtil;
import org.jetbrains.plugins.github.util.GithubUtil;

import java.util.Random;

import static com.intellij.openapi.vcs.Executor.cd;
import static git4idea.test.GitExecutor.git;

/**
 * @author Aleksey Pivovarov
 */
public abstract class GithubCreatePullRequestTestBase extends GithubTest {
  protected static final String PROJECT_URL = "https://github.com/ideatest1/PullRequestTest";
  protected static final String PROJECT_NAME = "PullRequestTest";
  protected String BRANCH_NAME;

  @Override
  protected void beforeTest() throws Exception {
    Random rnd = new Random();
    long time = Clock.getTime();
    BRANCH_NAME = "branch_" + getTestName(false) + "_" + DateFormatUtil.formatDate(time).replace('/', '-') + "_" + rnd.nextLong();

    registerHttpAuthService();

    cd(myProjectRoot.getPath());
    cloneRepo();
    createBranch();
    createChanges();
    initGitChecks();
  }

  @Override
  protected void afterTest() throws Exception {
    deleteRemoteBranch();
  }

  protected void deleteRemoteBranch() {
    GitRepository repository = GithubUtil.getGitRepository(myProject, myProjectRoot);
    if (repository != null) {
      ServiceManager.getService(Git.class).push(repository, "origin", PROJECT_URL, ":" + BRANCH_NAME, false);
    }
  }

  protected void registerDefaultCreatePullRequestDialogHandler(@NotNull final String branch, @NotNull final String user) {
    myDialogManager.registerDialogHandler(GithubCreatePullRequestDialog.class, new TestDialogHandler<GithubCreatePullRequestDialog>() {
      @Override
      public int handleDialog(GithubCreatePullRequestDialog dialog) {
        dialog.testSetRequestTitle(BRANCH_NAME);
        dialog.testSetFork(new GithubFullPath(user, PROJECT_NAME));
        dialog.testSetBranch(branch);
        dialog.testCreatePullRequest();
        return DialogWrapper.OK_EXIT_CODE;
      }
    });
  }

  protected void cloneRepo() {
    git("clone " + PROJECT_URL + " .");
    setGitIdentity(myProjectRoot);
    GitInit.refreshAndConfigureVcsMappings(myProject, myProjectRoot, myProjectRoot.getPath());
  }

  protected void addRemote(@NotNull String user) {
    git("remote add somename " + GithubUrlUtil.getCloneUrl(new GithubFullPath(user, PROJECT_NAME)));
  }

  protected void createBranch() {
    git("branch " + BRANCH_NAME);
    git("checkout " + BRANCH_NAME);
  }

  protected void createChanges() {
    VfsTestUtil.createFile(myProjectRoot, "file.txt", "file.txt content");
    git("add file.txt");
    git("commit -m changes");
  }
}


text:
<?php

namespace craft\migrations;

use craft\db\Migration;
use craft\db\Query;

/**
 * The class name is the UTC timestamp in the format of mYYMMDD_HHMMSS_migrationName
 */
class m151215_000000_rename_asset_permissions extends Migration
{
    /**
     * @inheritdoc
     */
    public function safeUp()
    {
        // Update permissions
        $permissions = (new Query())
            ->select(['id', 'name'])
            ->from(['{{%userpermissions}}'])
            ->where(['like', 'name', 'volume'])
            ->all($this->db);

        foreach ($permissions as $permission) {
            $newName = str_replace([
                'uploadtovolume',
                'createsubfoldersinvolume',
                'removefromvolume'
            ], [
                'saveassetinvolume',
                'createfoldersinvolume',
                'deletefilesandfoldersinvolume'
            ], $permission['name']);

            $this->update('{{%userpermissions}}', ['name' => $newName], ['id' => $permission['id']], [], false);
        }
    }

    /**
     * @inheritdoc
     */
    public function safeDown()
    {
        echo "m151215_000000_rename_asset_permissions cannot be reverted.\n";

        return false;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>App Engine Pipeline Framework Demonstrations</title>

Java App Engine Pipeline Framework

javadoc

        Demos

        Recursive GCD Calculation

        Letter count. Spawns a new sub-job for each word.


text:
var group__flexcan =
[
    [ "FlexCAN Driver", "group__flexcan__driver.html", "group__flexcan__driver" ],
    [ "FlexCAN HAL driver", "group__flexcan__hal.html", "group__flexcan__hal" ]
];


text:
use 5.006;
use strict;
use warnings;

package App::CPAN::Mini::Visit;
# ABSTRACT: explore each distribution in a minicpan repository
our $VERSION = '0.008'; # VERSION

use CPAN::Mini 0.572 ();
use Exception::Class::TryCatch 1.12 qw/ try catch /;
use File::Basename qw/ basename /;
use File::Find qw/ find /;
use File::pushd qw/ tempd /;
use Path::Class qw/ dir file /;
use Getopt::Lucid 0.16 qw/ :all /;
use Pod::Usage 1.35 qw/ pod2usage /;

use Archive::Extract 0.28 ();

my @option_spec = (
    Switch("help|h"), Switch("version|V"),
    Switch("quiet|q"), Param( "append|a", qr/(?:^$|(?:^path|dist$))/ )->default(''),
    Param("e|E"),      Param("minicpan|m"),
    Param("output|o"),
);

sub run {
    my ( $self, @args ) = @_;

    # get command line options
    my $opt = try eval { Getopt::Lucid->getopt( \@option_spec, \@args ) };
    for (catch) {
        if ( $_->isa('Getopt::Lucid::Exception::ARGV') ) {
            print "$_\n";
            # usage stuff
            return 1;
        }
        else {
            die $_;
        }
    }

    # handle "help" and "version" options
    return _exit_usage()   if $opt->get_help;
    return _exit_version() if $opt->get_version;

    # Set Archive::Extract globals
    # if quiet suppress warnings from Archive::Tar, etc.
    local $Archive::Extract::DEBUG      = 0;
    local $Archive::Extract::PREFER_BIN = 1;
    local $Archive::Extract::WARN       = $opt->get_quiet ? 0 : 1;

    # if -e/-E, then prepend to command
    if ( $opt->get_e ) {
        unshift @args, $^X, ( $^X > 5.009 ? '-E' : '-e' ), $opt->get_e;
    }

    # locate minicpan directory
    if ( !$opt->get_minicpan ) {
        my %config = CPAN::Mini->read_config;
        if ( $config{local} ) {
            $opt->merge_defaults( { minicpan => $config{local} } );
        }
    }

    # confirm minicpan directory that looks like minicpan
    return _exit_no_minicpan() if !$opt->get_minicpan;
    return _exit_bad_minicpan( $opt->get_minicpan ) if !-d $opt->get_minicpan;

    my $id_dir = dir( $opt->get_minicpan, qw/authors id/ );
    return _exit_bad_minicpan( $opt->get_minicpan ) if !-d $id_dir;

    # process all distribution tarballs in authors/id/...
    my $archive_re = qr{\.(?:tar\.(?:bz2|gz|Z)|t(?:gz|bz)|zip|pm\.gz)$}i;

    my $minicpan = dir( $opt->get_minicpan )->absolute;

    # save output by redirecting STDOUT if requested
    my ( $out_fh, $orig_stdout );
    if ( $opt->get_output ) {
        open $out_fh, ">", $opt->get_output;
        open $orig_stdout, "<&=STDOUT";
        open STDOUT, ">&=" . fileno $out_fh;
    }

    find(
        {
            no_chdir   => 1,
            follow     => 0,
            preprocess => sub { my @files = sort @_; return @files },
            wanted     => sub {
                return unless /$archive_re/;
                # run code if program/args given otherwise print name
                if (@args) {
                    return if $_ =~ /pm\.gz$/io; # not an archive, just a file
                    my @cmd = @args;
                    if ( $opt->get_append ) {
                        if ( $opt->get_append eq 'dist' ) {
                            my $distname = $_;
                            my $prefix = dir( $minicpan, qw/authors id/ );
                            $distname =~ s{^$prefix[\\/].[\\/]..[\\/]}{};
                            push @cmd, $distname;
                        }
                        else {
                            push @cmd, $_;
                        }
                    }
                    _visit( $_, @cmd );
                }
                else {
                    print "$_\n";
                }
            },
        },
        $minicpan
    );

    # restore STDOUT and close output file
    if ( $opt->get_output ) {
        open STDOUT, ">&=" . fileno $orig_stdout;
        close $out_fh;
    }

    return 0; # exit code
}

sub _exit_no_minicpan {
    print STDERR << "END_NO_MINICPAN";
No minicpan configured.

END_NO_MINICPAN
    return 1;
}

sub _exit_bad_minicpan {
    my ($dir) = @_;
    die "requires directory argument" unless defined $dir;
    print STDERR << "END_BAD_MINICPAN";
Directory '$dir' does not appear to be a CPAN repository.

END_BAD_MINICPAN
    return 1;
}

sub _exit_usage {
    my $exe = basename($0);
    print STDERR << "END_USAGE";
Usage:
  $exe [OPTIONS] [PROGRAM]

  $exe [OPTIONS] -- [PROGRAM] [ARGS]

Options:

 --append|-a        --append=dist -> append distname after ARGS
                    --append=path -> append tarball path after ARGS

 -e|-E              run next argument via 'perl -E'

 --help|-h          this usage info

 --minicpan|-m      directory of a minicpan (defaults to local minicpan
                    from CPAN::Mini config file)

 --output|-o        file to save output instead of sending to terminal

 --quiet|-q         silence warnings and suppress STDERR from tar

 --version|-V       $exe program version

 --                 indicates the end of options for $exe

END_USAGE
    return 1;
}

sub _exit_version {
    print STDERR basename($0) . ": $VERSION\n";
    return 1;
}

sub _visit {
    my ( $archive, @cmd_line ) = @_;

    my $tempd = tempd;

    my $ae = Archive::Extract->new( archive => $archive );

    my $olderr;

    # stderr > /dev/null if quiet
    if ( !$Archive::Extract::WARN ) {
        open $olderr, ">&STDERR";
        open STDERR, ">", File::Spec->devnull;
    }

    my $extract_ok = $ae->extract;

    # restore stderr if quiet
    if ( !$Archive::Extract::WARN ) {
        open STDERR, ">&", $olderr;
        close $olderr;
    }

    if ( !$extract_ok ) {
        warn "Couldn't extract '$archive'\n" if $Archive::Extract::WARN;
        return;
    }

    # most distributions unpack a single directory that we must enter
    # but some behave poorly and unpack to the current directory
    my @children = dir()->children;
    if ( @children == 1 && -d $children[0] ) {
        chdir $children[0];
    }

    # execute command
    my $rc = system(@cmd_line);
    if ( $rc == -1 ) {
        warn "Error running '@cmd_line': $!\n";
    }

    return;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

App::CPAN::Mini::Visit - explore each distribution in a minicpan repository

=head1 VERSION

version 0.008

=head1 SYNOPSIS

    #!/usr/bin/perl
    use App::CPAN::Mini::Visit;
    exit App::CPAN::Mini::Visit->run;

=head1 DESCRIPTION

This module contains the guts of the L<visitcpan> program.  See documentation of
that program for details on features and command line options.

=head1 USAGE

=head2 C<run>

    exit App::CPAN::Mini::Visit->run();

Executes the program, processing command line arguments and traversing
a minicpan repository.  Returns an exit code.

=head1 SEE ALSO

=over 4

=item *

L<CPAN::Mini>

=back

=for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan

=head1 SUPPORT

=head2 Bugs / Feature Requests

Please report any bugs or feature requests through the issue tracker
at L<https://github.com/dagolden/App-CPAN-Mini-Visit/issues>.
You will be notified automatically of any progress on your issue.

=head2 Source Code

This is open source software.  The code repository is available for
public review and contribution under the terms of the license.

L<https://github.com/dagolden/App-CPAN-Mini-Visit>

  git clone https://github.com/dagolden/App-CPAN-Mini-Visit.git

=head1 AUTHOR

David Golden <dagolden@cpan.org>

=head1 CONTRIBUTOR

Ricardo Signes <rjbs@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2014 by David Golden.

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004

=cut


text:
Command Line
============

Simpleflow comes with a `simpleflow` command-line utility that can be used to list workflows against SWF, boot decider or activity workers (with multiprocessing), and a few other goodies.

List Workflow Executions
------------------------

    $ simpleflow workflow.list TestDomain
    basic-example-1438722273  basic  OPEN

Workflow Execution Status
-------------------------

    $ simpleflow --header workflow.info TestDomain basic-example-1438722273
    domain      workflow_type.name    workflow_type.version      task_list  workflow_id               run_id                                          tag_list      execution_time  input
    TestDomain  basic                 example                               basic-example-1438722273  22QFVi362TnCh6BdoFgkQFlocunh24zEOemo1L12Yl5Go=                          1.70  {u'args': [1], u'kwargs': {}}

Tasks Status
------------

You can check the status of the workflow execution with::

    $ simpleflow --header workflow.tasks DOMAIN WORKFLOW_ID [RUN_ID] --nb-tasks 3
    $ simpleflow --header workflow.tasks TestDomain basic-example-1438722273
    Tasks                     Last State    Last State Time             Scheduled Time
    examples.basic.increment  scheduled     2015-08-04 23:04:34.510000  2015-08-04 23:04:34.510000
    $ simpleflow --header workflow.tasks TestDomain basic-example-1438722273
    Tasks                     Last State    Last State Time             Scheduled Time
    examples.basic.double     completed     2015-08-04 23:06:19.200000  2015-08-04 23:06:17.738000
    examples.basic.delay      completed     2015-08-04 23:08:18.402000  2015-08-04 23:06:17.738000
    examples.basic.increment  completed     2015-08-04 23:06:17.503000  2015-08-04 23:04:34.510000

Profiling
---------

You can profile the execution of the workflow with::

    $ simpleflow --header workflow.profile TestDomain basic-example-1438722273
    Task                                 Last State    Scheduled           Time Scheduled  Start               Time Running  End                 Percentage of total time
    activity-examples.basic.double-1     completed     2015-08-04 23:06              0.07  2015-08-04 23:06            1.39  2015-08-04 23:06                        1.15
    activity-examples.basic.increment-1  completed     2015-08-04 23:04            102.20  2015-08-04 23:06            0.79  2015-08-04 23:06                        0.65

Controlling SWF access
----------------------

The SWF region is controlled by the environment variable `AWS_DEFAULT_REGION`. This variable
comes from the legacy "simple-workflow" project. The option might be exposed through a
`--region` option in the future (if you want that, please open an issue).

The SWF domain is controlled by the `--domain` on most simpleflow commands. It can also
be set via the `SWF_DOMAIN` environment variable. In case both are supplied, the
command-line value takes precedence over the environment variable.

Note that some simpleflow commands expect the domain to be passed as a positionnal argument.
In that case the environment variable has no effect for now.

The number of retries for accessing SWF can be controlled via `SWF_CONNECTION_RETRIES`
(defaults to 5).

The identity of SWF activity workers and deciders can be controlled via `SIMPLEFLOW_IDENTITY`
which should be a JSON-serialized string representing `{ "key": "value" }` pairs that
adds up (or override) the basic identity provided by simpleflow. If some value is null in
this JSON map, then the key is removed from the final SWF identity.

Controlling log verbosity
-------------------------

You can control log verbosity via the `LOG_LEVEL` environment variable. Default is `INFO`. For instance,
the following command will start a decider with `DEBUG` logs:

    $ LOG_LEVEL=DEBUG simpleflow decider.start --domain TestDomain --task-list test examples.basic.BasicWorkflow


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using Microsoft.Languages.Editor.Text;

namespace Microsoft.R.Editor.SmartIndent {
    /// <summary>
    /// Provides methods that compute the desired indentation for a line.
    /// </summary>
    public interface ISmartIndenter {
        /// <summary>
        /// Gets the desired indentation of editor line.
        /// </summary>
        /// <returns>The number of spaces to place at the start of the line,
        /// or null if there is no desired indentation.</returns>
        int? GetDesiredIndentation(IEditorLine line);
    }
}


text:
namespace DKFoundation::Private
{
    // base64 encode/decode
    template <typename BaseCharT> struct Base64;
    template <> struct Base64<char>
    {
        static const char* Base64Chars()
        {
            return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        }
        static FORCEINLINE bool IsBase64(char c)
        {
            return ((c == '+') || (c == '/') || isalnum(c));
        }
    };
    template <> struct Base64<wchar_t>
    {
        static const wchar_t* Base64Chars()
        {
            return L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        }
        static FORCEINLINE bool IsBase64(wchar_t c)
        {
            return ((c == L'+') || (c == '/') || iswalnum(c));
        }
    };

    template <typename BaseCharT> void Base64Encode(unsigned char const* bytes_to_encode, size_t in_len, DKArray<BaseCharT>& output)
    {
        output.Clear();
        output.Reserve(((in_len * 4) / 3) + 3);

        int i = 0;
        int j = 0;
        unsigned char char_array_3[3];
        unsigned char char_array_4[4];

        while (in_len--) {
            char_array_3[i++] = *(bytes_to_encode++);
            if (i == 3) {
                char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
                char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
                char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
                char_array_4[3] = char_array_3[2] & 0x3f;

                for (i = 0; (i < 4); i++)
                    output.Add(Base64<BaseCharT>::Base64Chars()[char_array_4[i]]);
                i = 0;
            }
        }

        if (i)
        {
            for (j = i; j < 3; j++)
                char_array_3[j] = '\0';

            char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
            char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
            char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
            char_array_4[3] = char_array_3[2] & 0x3f;

            for (j = 0; (j < i + 1); j++)
                output.Add(Base64<BaseCharT>::Base64Chars()[char_array_4[j]]);

            while ((i++ < 3))
                output.Add('=');
        }
        //return output;
    }

    template <typename BaseCharT> bool Base64Decode(const BaseCharT* encoded_string, size_t in_len, DKBuffer* output)
    {
        auto IndexOfBase64Char = [](BaseCharT c) -> int
        {
            for (int i = 0; i < 64; ++i)
                if (c == Base64<BaseCharT>::Base64Chars()[i])
                    return i;
            return -1;
        };

        int i = 0;
        int j = 0;
        int in_ = 0;
        char char_array_4[4], char_array_3[3];
        DKArray<char> result;
        result.Reserve((in_len * 3) / 4 + 3);

        while (in_len-- && (encoded_string[in_] != '=') && Base64<BaseCharT>::IsBase64(encoded_string[in_]))
        {
            char_array_4[i++] = static_cast<char>(encoded_string[in_]); in_++;
            if (i == 4)
            {
                for (i = 0; i < 4; ++i)
                    char_array_4[i] = IndexOfBase64Char(char_array_4[i]);

                char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
                char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
                char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

                for (i = 0; (i < 3); i++)
                    result.Add(char_array_3[i]);

                i = 0;
            }
        }

        if (i) {
            for (j = i; j < 4; j++)
                char_array_4[j] = 0;

            for (j = 0; j < 4; j++)
                char_array_4[j] = IndexOfBase64Char(char_array_4[j]);

            char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
            char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
            char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

            for (j = 0; (j < i - 1); j++)
                result.Add(char_array_3[j]);
        }
        if (result.Count())
        {
            output->SetContent((const char*)result, result.Count());
            return true;
        }
        return false;
    }

    static DKObject<DKBuffer> GetHTTPContent(const DKString& url, DKAllocator& alloc)
    {
        if (url.Length() == 0)
            return NULL;

        DKStringU8 filenameUTF8(url);
        if (filenameUTF8 == "" || filenameUTF8.Bytes() == 0)
            return NULL;

        // initialize http
        xmlNanoHTTPInit();

        // connect
        void* ctxt = xmlNanoHTTPOpen((const char*)filenameUTF8, NULL);
        if (ctxt == NULL)
            return NULL;

        DKObject<DKBuffer> data = NULL;

        int len = xmlNanoHTTPContentLength(ctxt);
        if (len > 0)
        {
            void* buffer = DKMalloc(len);
            int recv = xmlNanoHTTPRead(ctxt, buffer, len); // download
            if (recv == len)
            {
                data = DKBuffer::Create(buffer, len, alloc);
            }
            DKFree(buffer);
        }
        xmlNanoHTTPClose(ctxt);
        xmlNanoHTTPCleanup();

        return data;
    }

    static DKObject<DKBuffer> GetFTPContent(const DKString& url, DKAllocator& alloc)
    {
        if (url.Length() == 0)
            return NULL;

        DKStringU8 filenameUTF8(url);
        if (filenameUTF8 == "" || filenameUTF8.Bytes() == 0)
            return NULL;

        xmlNanoFTPInit();

        void* ctxt = xmlNanoFTPOpen((const char*)filenameUTF8);
        if (ctxt == NULL)
            return NULL;

        DKObject<DKBuffer> data = NULL;

        size_t	bufferSize = 4096;
        size_t	received = 0;
        char* buffer = (char*)DKMalloc(bufferSize);

        while (true)
        {
            int recv = xmlNanoFTPRead(ctxt, buffer + received, static_cast<int>(bufferSize - received));
            received += recv;

            if (recv < 0)		// error!
            {
                break;
            }
            else if (recv == 0)	// succeeded.
            {
                data = DKBuffer::Create(buffer, received, alloc);
                break;
            }
            if (received + 100 > bufferSize)
            {
                bufferSize += 4096;
                char* tmp = (char*)DKRealloc(buffer, bufferSize);
                if (tmp == NULL)
                {
                    DKLog("Warning: Out of memory!\n");
                    break;
                }
                buffer = tmp;
            }
        }
        DKFree(buffer);

        xmlNanoFTPClose(ctxt);
        xmlNanoFTPCleanup();

        return data;
    }
}
using namespace DKFoundation;

DKBuffer::DKBuffer(DKAllocator& alloc)
	: contentPtr(NULL)
	, contentLength(0)
	, allocator(&alloc)
{
}

DKBuffer::DKBuffer(const void* p, size_t s, DKAllocator& alloc)
	: contentPtr(NULL)
	, contentLength(0)
	, allocator(&alloc)
{
	SetContent(p, s);
}

DKBuffer::DKBuffer(const DKData* buff, DKAllocator& alloc)
	: contentPtr(NULL)
	, contentLength(0)
	, allocator(&alloc)
{
	SetContent(buff);
}

DKBuffer::DKBuffer(const DKBuffer& b)
	: contentPtr(NULL)
	, contentLength(0)
	, allocator(b.allocator)
{
	SetContent(b.contentPtr, b.contentLength);
}

DKBuffer::DKBuffer(DKBuffer&& b)
	: contentPtr(NULL)
	, contentLength(0)
	, allocator(b.allocator)
{
	this->contentPtr = b.contentPtr;
	this->contentLength = b.contentLength;
	b.contentPtr = NULL;
	b.contentLength = 0;
}

DKBuffer::~DKBuffer()
{
#ifdef DKGL_DEBUG_ENABLED
	if (sharedLock.TryLock())
	{
		sharedLock.Unlock();
	}
	else
	{
		DKERROR_THROW("Data Locked!");
	}
#endif

	if (contentPtr)
		allocator->Dealloc(contentPtr);
}

size_t DKBuffer::Length() const
{
	return contentLength;
}

bool DKBuffer::SetLength(size_t len)
{
	if (contentLength != len)
	{
		DKCriticalSection<DKSharedLock> guard(this->sharedLock);
		if (len > 0)
		{
			void* p = this->allocator->Realloc(contentPtr, len);
			if (p)
			{
				contentPtr = p;
				contentLength = len;
			}
			else
			{
				DKLog("DKBuffer error: Out of memory!");
				return false;
			}
		}
		else
		{
			if (contentPtr)
				allocator->Dealloc(contentPtr);
			contentPtr = NULL;
			contentLength = 0;
		}
	}
	return true;
}

bool DKBuffer::Base64Encode(DKStringU8& strOut) const
{
	bool ret = false;
	const void* p = this->LockShared();
	size_t inputLength = this->Length();
	if (p && inputLength > 0)
	{
		DKArray<char> result;
		Private::Base64Encode((const unsigned char*)p, inputLength, result);
		if (result.Count() > 0)
		{
			strOut.SetValue((const char*)result, result.Count());
			ret = true;
		}
	}
	this->UnlockShared();
	return ret;
}

bool DKBuffer::Base64Encode(DKStringW& strOut) const
{
	bool ret = false;
	const void* p = this->LockShared();
	size_t inputLength = this->Length();
	if (p && inputLength > 0)
	{
		DKArray<wchar_t> result;
		Private::Base64Encode((const unsigned char*)p, inputLength, result);
		if (result.Count() > 0)
		{
			strOut.SetValue((const wchar_t*)result, result.Count());
			ret = true;
		}
	}
	this->UnlockShared();
	return ret;
}

DKObject<DKBuffer> DKBuffer::Base64Decode(const DKStringU8& str, DKAllocator& alloc)
{
	DKObject<DKBuffer> buff = DKOBJECT_NEW DKBuffer(alloc);
	if (Private::Base64Decode((const char*)str, str.Bytes(), buff))
		return buff;
	return NULL;
}

DKObject<DKBuffer> DKBuffer::Base64Decode(const DKStringW& str, DKAllocator& alloc)
{
	DKObject<DKBuffer> buff = DKOBJECT_NEW DKBuffer(alloc);
	if (Private::Base64Decode((const wchar_t*)str, str.Length(), buff))
		return buff;
	return NULL;
}

DKObject<DKBuffer> DKBuffer::Compress(const DKCompressor& compressor, DKAllocator& alloc) const
{
	const void* p = this->LockShared();
	size_t inputLength = this->Length();
	DKObject<DKBuffer> result = Compress(compressor, p, inputLength, alloc);
	this->UnlockShared();
	return result;
}

DKObject<DKBuffer> DKBuffer::Compress(const DKCompressor& compressor, const void* p, size_t len, DKAllocator& alloc)
{
	if (p && len > 0)
	{
		DKObject<DKBuffer> output = DKBuffer::Create(0, 0, alloc);
		DKBufferStream outputStream(output);
		DKDataStream inputStream(DKData::StaticData(p, len));

		if (compressor.Compress(&inputStream, &outputStream))
			return outputStream.Buffer();
	}
	return NULL;
}

DKObject<DKBuffer> DKBuffer::Decompress(DKAllocator& alloc) const
{
	const void* p = this->LockShared();
	size_t len = this->Length();
	DKObject<DKBuffer> result = Decompress(p, len, alloc);
	this->UnlockShared();
	return result;
}

DKObject<DKBuffer> DKBuffer::Decompress(const void* p, size_t len, DKAllocator& alloc)
{
	if (p && len > 4)
	{
		DKObject<DKBuffer> output = DKBuffer::Create(0, 0, alloc);
		DKBufferStream outputStream(output);
		DKDataStream inputStream(DKData::StaticData(p, len));

		if (DKCompressor::Decompress(&inputStream, &outputStream))
			return outputStream.Buffer();
	}
	return NULL;
}

DKObject<DKBuffer> DKBuffer::Create(const DKString& url, DKAllocator& alloc)
{
	DKString filename;

	if (url.Left(7).CompareNoCase(L"http://") == 0)
		return Private::GetHTTPContent(url, alloc);
	else if (url.Left(6).CompareNoCase(L"ftp://") == 0)
		return Private::GetFTPContent(url, alloc);
	else if (url.Left(7).CompareNoCase(L"file://") == 0)
	{
		filename = url.Right(7);
		if (filename.Length() < 1)
			return NULL;
#ifdef _WIN32
		{
			if ((filename[0] == L'\\' || filename[0] == L'/') &&
				filename[2] == L':' &&
				(filename[3] == L'\\' || filename[3] == L'/'))
				filename = filename.Right(1);
		}
#endif
	}
	else
	{
		filename = url;
	}

	if (filename.Length() > 0)
	{
		DKObject<DKFile> f = DKFile::Create(filename, DKFile::ModeOpenReadOnly, DKFile::ModeShareAll);
		DKFile::FileInfo info;
		if (f && f->GetInfo(info) && info.size > 0)
		{
			return f->Read(info.size, alloc);
		}
	}
	return NULL;
}

DKObject<DKBuffer> DKBuffer::Create(const void* p, size_t s, DKAllocator& alloc)
{
	DKObject<DKBuffer> data = DKObject<DKBuffer>::Alloc(alloc);
	data->SetContent(p, s);
	return data;
}

DKObject<DKBuffer> DKBuffer::Create(const DKData* p, DKAllocator& alloc)
{
	DKObject<DKBuffer> data = DKObject<DKBuffer>::Alloc(alloc);
	data->SetContent(p);
	return data;
}

DKObject<DKBuffer> DKBuffer::Create(DKStream* s, DKAllocator& alloc)
{
	if (s == NULL || !s->IsReadable())
		return NULL;

	DKStream::Position len = s->RemainLength();
	if (len > 0)
	{
		DKObject<DKBuffer> p = DKBuffer::Create(NULL, len, alloc);
		if (p)
		{
			void* buff = p->LockExclusive();
			size_t bytesRead = s->Read(buff, len);
			p->UnlockExclusive();

			if (bytesRead == len)
				return p;
		}
	}
	return NULL;
}

size_t DKBuffer::SetContent(const void* p, size_t s)
{
	DKCriticalSection<DKSharedLock> guard(this->sharedLock);

	if (contentLength == s)
	{
		if (s > 0 && p)
		{
			memcpy(contentPtr, p, s);
		}
		else if (s > 0)
		{
			memset(contentPtr, 0, s);
		}
	}
	else
	{
		if (s > 0)
		{
			void* ptr = allocator->Alloc(s);

			if (p)
				memcpy(ptr, p, s);
			else
				memset(ptr, 0, s);

			if (contentPtr)
				allocator->Dealloc(contentPtr);

			this->contentPtr = ptr;
			this->contentLength = s;
		}
		else
		{
			if (contentPtr)
				allocator->Dealloc(contentPtr);

			contentPtr = NULL;
			contentLength = 0;
		}
	}
	return contentLength;
}

size_t DKBuffer::SetContent(const DKData* buff)
{
	size_t ret = 0;
	if (buff)
	{
		const void* p = buff->LockShared();
		ret = SetContent(p, buff->Length());
		buff->UnlockShared();
	}
	else
	{
		ret = SetContent(0, 0);
	}
	return ret;
}

DKBuffer& DKBuffer::operator = (const DKBuffer& b)
{
	SetContent(&b);
	return *this;
}

DKBuffer& DKBuffer::operator = (DKBuffer&& b)
{
	if (this != &b)
	{
		DKCriticalSection<DKSharedLock> guard(this->sharedLock);

		if (this->contentPtr)
			this->allocator->Dealloc(this->contentPtr);

		this->contentPtr = b.contentPtr;
		this->contentLength = b.contentLength;
		this->allocator = b.allocator;
		b.contentPtr = NULL;
		b.contentLength = 0;
	}
	return *this;
}

size_t DKBuffer::CopyContent(void* p, size_t offset, size_t length) const
{
	const char* ptr = reinterpret_cast<const char*>(this->LockShared());
	size_t contentLength = this->Length();
	size_t ret = 0;
	if (p && offset < contentLength)
	{
		length = Min(length, contentLength - offset);
		memcpy(p, &ptr[offset], length);
		ret = length;
	}
	this->UnlockShared();
	return ret;
}

void DKBuffer::SwitchAllocator(DKAllocator& alloc)
{
	if (&alloc != this->allocator)
	{
		DKCriticalSection<DKSharedLock> guard(this->sharedLock);

		if (contentLength > 0)
		{
			void* p = alloc.Alloc(contentLength);
			memcpy(p, contentPtr, contentLength);

			this->contentPtr = p;
			this->allocator->Dealloc(contentPtr);
		}
		this->allocator = &alloc;
	}
}

DKAllocator& DKBuffer::Allocator() const
{
	return *this->allocator;
}

void* DKBuffer::LockContent()
{
	return contentPtr;
}

void DKBuffer::UnlockContent()
{
}

const void* DKBuffer::LockShared() const
{
	sharedLock.LockShared();
	return contentPtr;
}

bool DKBuffer::TryLockShared(const void ** ptr) const
{
	if (sharedLock.TryLockShared())
	{
		if (ptr)
			*ptr = contentPtr;
		return true;
	}
	return false;
}

void DKBuffer::UnlockShared() const
{
	sharedLock.UnlockShared();
}

void* DKBuffer::LockExclusive()
{
	sharedLock.Lock();
	return contentPtr;
}

bool DKBuffer::TryLockExclusive(void ** ptr)
{
	if (sharedLock.TryLock())
	{
		if (ptr)
			*ptr = contentPtr;
		return true;
	}
	return false;
}

void DKBuffer::UnlockExclusive()
{
	sharedLock.Unlock();
}


text:
import tabUrl from './lib/ActiveTabUrl';
import jobFeedUrl from './lib/HasjobFeedUrl';
import { checkStatus, responseText, handleError } from './lib/RequestUtils';
import { textToXml, xmlToHtml, appendData } from './lib/HtmlUtils';

const processTabUrl = new Promise(tabUrl);

processTabUrl
  .then(jobFeedUrl)
  .then(fetch)
  .then(checkStatus)
  .then(responseText)
  .then(textToXml)
  .then(xmlToHtml)
  .then(appendData)
  .catch(handleError);


text:
var path = require('path');
var webpack = require('webpack');

module.exports = {
    devtool: 'eval',
    entry: [
        'webpack-dev-server/client?http://localhost:3000',
        'webpack/hot/only-dev-server',
        './src/home/index'
    ],
    output: {
        path: path.join(__dirname, 'build/public'),
        filename: 'bundle.js',
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin()
    ],
    module: {
        loaders: [{
            test: /\.js$/,
            loaders: ['react-hot', 'babel'],
            include: path.join(__dirname, 'src')
        }, {
            test: /\.s?css$/,
            loader: "style!css!sass"
        }]
    }
};


text:
package org.apereo.cas.oidc.authn;

import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.oauth.authenticator.OAuth20AccessTokenAuthenticator;
import org.apereo.cas.support.oauth.util.OAuth20Utils;
import org.apereo.cas.ticket.OAuth20TokenSigningAndEncryptionService;
import org.apereo.cas.ticket.accesstoken.OAuth20AccessToken;
import org.apereo.cas.ticket.registry.TicketRegistry;
import org.apereo.cas.token.JwtBuilder;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.jose4j.jwt.MalformedClaimException;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.credentials.TokenCredentials;
import org.pac4j.core.profile.CommonProfile;

import java.util.Optional;

/**
 * This is {@link OidcAccessTokenAuthenticator}.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@Slf4j
public class OidcAccessTokenAuthenticator extends OAuth20AccessTokenAuthenticator {
    private final OAuth20TokenSigningAndEncryptionService idTokenSigningAndEncryptionService;
    private final ServicesManager servicesManager;

    public OidcAccessTokenAuthenticator(final TicketRegistry ticketRegistry,
                                        final OAuth20TokenSigningAndEncryptionService signingAndEncryptionService,
                                        final ServicesManager servicesManager,
                                        final JwtBuilder accessTokenJwtBuilder) {
        super(ticketRegistry, accessTokenJwtBuilder);
        this.idTokenSigningAndEncryptionService = signingAndEncryptionService;
        this.servicesManager = servicesManager;
    }

    @Override
    protected CommonProfile buildUserProfile(final TokenCredentials tokenCredentials, final WebContext webContext, final OAuth20AccessToken accessToken) {
        try {
            val profile = super.buildUserProfile(tokenCredentials, webContext, accessToken);
            validateIdTokenIfAny(accessToken, profile);
            return profile;
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * Validate id token if any.
     *
     * @param accessToken the access token
     * @param profile     the profile
     * @throws MalformedClaimException the malformed claim exception
     */
    protected void validateIdTokenIfAny(final OAuth20AccessToken accessToken, final CommonProfile profile) throws MalformedClaimException {
        if (StringUtils.isNotBlank(accessToken.getIdToken())) {
            val service = OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, accessToken.getClientId());
            val idTokenResult = idTokenSigningAndEncryptionService.decode(accessToken.getIdToken(), Optional.ofNullable(service));
            profile.setId(idTokenResult.getSubject());
            profile.addAttributes(idTokenResult.getClaimsMap());
        }
    }
}


text:
package proxy

import (
	"bytes"
	"crypto/md5"
	"encoding/binary"
	"fmt"
	"github.com/crunchydata/crunchy-proxy/config"
	"github.com/golang/glog"
	"net"
)

const PROTOCOL_VERSION int32 = 196608

/* Authentication Method constants. */
const (
	AUTHENTICATION_OK            int32 = 0
	AUTHENTICATION_KERBEROS_V5   int32 = 2
	AUTHENTICATION_CLEAR_TEXT    int32 = 3
	AUTHENTICATION_MD5           int32 = 5
	AUTHENTICATION_SCM           int32 = 6
	AUTHENTICATION_GSS           int32 = 7
	AUTHENTICATION_GSS_CONTINUTE int32 = 8
	AUTHENTICATION_SSPI          int32 = 9
)

/* PostgreSQL Message Type constants. */
const (
	AUTHENTICATION_MESSAGE_TYPE   byte = 'R'
	ERROR_MESSAGE_TYPE            byte = 'E'
	EMPTY_QUERY_MESSAGE_TYPE      byte = 'I'
	DESCRIBE_MESSAGE_TYPE         byte = 'D'
	ROW_DESCRIPTION_MESSAGE_TYPE  byte = 'T'
	DATA_ROW_MESSAGE_TYPE         byte = 'D'
	QUERY_MESSAGE_TYPE            byte = 'Q'
	COMMAND_COMPLETE_MESSAGE_TYPE byte = 'C'
	TERMINATE_MESSAGE_TYPE        byte = 'X'
	NOTICE_MESSAGE_TYPE           byte = 'N'
	PASSWORD_MESSAGE_TYPE         byte = 'p'
)

func NullTermToStrings(b []byte) (s []string) {
	var zb = []byte{0}
	for _, x := range bytes.Split(b, zb) {
		s = append(s, string(x))
	}
	if len(s) > 0 && s[len(s)-1] == "" {
		s = s[:len(s)-1]
	}
	return
}

func Connect(node *config.Node) (net.Conn, error) {
	glog.Infof("Connecting to %s\n", node.HostPort)
	connection, err := net.Dial("tcp", node.HostPort)

	if err != nil {
		glog.Errorf("Error: %s\n", err.Error())
	}

	if config.Cfg.Credentials.SSL.Enable {
		glog.Infoln("SSL is enabled. Determine if connection upgrade is required.")
		var message []byte

		/*
		 * First determine if SSL is allowed by the backend. To do this, send an
		 * SSL request. The response from the backend will be a single byte
		 * message. If the value is 'S', then SSL connections are allowed and an
		 * upgrade to the connection should be attempted. If the value is 'N',
		 * then the backend does not support SSL connections.
		 */

		/* Create the SSL request message. */
		messageLength := make([]byte, 4)
		sslRequestCode := make([]byte, 4)

		binary.BigEndian.PutUint32(messageLength, uint32(8))
		message = append(message, messageLength...)
		binary.BigEndian.PutUint32(sslRequestCode, uint32(80877103))
		message = append(message, sslRequestCode...)

		/* Send the SSL request message. */
		_, err := connection.Write(message)

		if err != nil {
			glog.Errorln("[proxy] Error sending SSL request to backend.")
			glog.Errorf("[proxy] %s\n", err.Error())
		}

		/* Received SSL response message. */
		_, err = connection.Read(message)

		if err != nil {
			glog.Errorln("[proxy] Error receiving SSL response from backend.")
			glog.Errorf("Error: %s\n", err.Error())
		}

		/*
		 * If SSL is not allowed by the backend then close the connection and
		 * throw an error.
		 */
		if len(message) > 0 && message[0] != 'S' {
			glog.Errorln("[proxy] The backend does not allow SSL connections.")
		} else {
			glog.Infoln("[proxy] SSL connections are allowed.")
			glog.Infoln("[proxy] Attempting to upgrade connection.")
			connection = upgradeClientConnection(node, connection)
			glog.Infoln("[protocol] Connectionn successfully upgraded.")
		}
	}

	return connection, nil
}

/*
 * Handle authentication requests that are sent by the backend to the client.
 *
 * connection - the connection to authenticate against.
 * message - the authentication message sent by the backend.
 */
func handleAuthenticationRequest(connection net.Conn, message []byte) bool {
	var msgLength int32
	var authType int32

	// Read message length.
	reader := bytes.NewReader(message[1:5])
	binary.Read(reader, binary.BigEndian, &msgLength)

	// Read authentication type.
	reader.Reset(message[5:9])
	binary.Read(reader, binary.BigEndian, &authType)

	switch authType {
	case AUTHENTICATION_KERBEROS_V5:
		glog.Fatalln("[protocol] KerberosV5 authentication is not currently supported.")
	case AUTHENTICATION_CLEAR_TEXT:
		glog.V(2).Infoln("[protocol] Authenticating with clear text password.")
		return handleAuthClearText(connection)
	case AUTHENTICATION_MD5:
		glog.V(2).Infoln("[protocol] Authenticating with MD5 password.")
		return handleAuthMD5(connection, message)
	case AUTHENTICATION_SCM:
		glog.Fatalln("[protocol] SCM authentication is not currently supported.")
	case AUTHENTICATION_GSS:
		glog.Fatalln("[protocol] GSS authentication is not currently supported.")
	case AUTHENTICATION_GSS_CONTINUTE:
		glog.Fatalln("[protocol] GSS authentication is not currently supported.")
	case AUTHENTICATION_SSPI:
		glog.Fatalln("[protocol] SSPI authentication is not currently supported.")
	case AUTHENTICATION_OK:
		/* Covers the case where the authentication type is 'cert'. */
		return true
	default:
		glog.Fatalf("[protocol] Unknown authentication method: %d\n", authType)
	}

	return false
}

/*
 * Handle authentication with a clear text password. If the authentication is
 * successful, then return true otherwise false.
 *
 * connection - the connection to authenticate against.
 */
func handleAuthClearText(connection net.Conn) bool {
	var writeLength, readLength int
	var response []byte
	var err error

	// Create the password message.
	passwordMessage := createPasswordMessage(config.Cfg.Credentials.Password)

	// Send the password message to the backend.
	writeLength, err = connection.Write(passwordMessage)

	// Check that write was successful.
	if err != nil {
		glog.Errorln("[protocol] Error sending password message to the backend.")
		glog.Errorf("[protocol] %s", err.Error())
	}

	glog.V(2).Infof("[protocol] %d bytes sent to the backend.\n", writeLength)

	// Read response from password message.
	readLength, err = connection.Read(response)

	// Check that read was successful.
	if err != nil {
		glog.Errorln("[protocol] Error receiving authentication response from the backend.")
		glog.Errorf("[protocol] %s\n", err.Error())
	}

	glog.V(2).Infof("[protocol] %d bytes received from the backend.\n", readLength)

	return isAuthenticationOk(response)
}

/*
 * Create a MD5 password.  The password is created using the following format:
 * md5(md5(password+username)+salt)
 *
 * username - the username of the authenticating user.
 * password - the password of the authenticating user.
 * salt - the random salt used in creation of the MD5 password.
 */
func createMD5Password(username string, password string, salt string) string {
	// Concatenate the password and the username together.
	passwordString := fmt.Sprintf("%s%s", password, username)

	// Compute the MD5 sum of the password+username string.
	passwordString = fmt.Sprintf("%x", md5.Sum([]byte(passwordString)))

	// Compute the MD5 sum of the password hash and the salt
	passwordString = fmt.Sprintf("%s%s", passwordString, salt)
	return fmt.Sprintf("md5%x", md5.Sum([]byte(passwordString)))
}

/*
 * Create a PG password message.
 *
 * password - the password to include in the payload of the message.
 */
func createPasswordMessage(password string) []byte {
	var message []byte

	// Create an MD5 password value.
	// Set the message type.
	message = append(message, PASSWORD_MESSAGE_TYPE)

	// Initialize the message length to zero.
	messageLength := make([]byte, 4)
	binary.BigEndian.PutUint32(messageLength, uint32(0))
	message = append(message, messageLength...)

	// Append the MD5 password to the message.
	message = append(message, password...)

	// null terminate the message.
	message = append(message, 0)

	/*
	 * Update the message length, subtracting the length of the message type
	 * byte.
	 */
	binary.BigEndian.PutUint32(messageLength, uint32(len(message)-1))
	copy(message[1:], messageLength)

	return message
}

/*
 * Handle authentication with a MD5 password. If the authentication is
 * successful, then return true otherwise false.
 *
 * connection - the connection to authenticate against.
 */
func handleAuthMD5(connection net.Conn, message []byte) bool {
	var writeLength, readLength int
	var err error

	// Get the authentication credentials.
	username := config.Cfg.Credentials.Username
	password := config.Cfg.Credentials.Password
	salt := string(message[9:13])

	password = createMD5Password(username, password, salt)

	// Create the password message.
	passwordMessage := createPasswordMessage(password)

	// Send the password message to the backend.
	writeLength, err = connection.Write(passwordMessage)

	// Check that write was successful.
	if err != nil {
		glog.Errorln("[protocol] Error sending password message to the backend.")
		glog.Errorf("[protocol] %s", err.Error())
	}

	glog.V(2).Infof("[protocol] %d bytes sent to the backend.\n", writeLength)

	// Read response from password message.
	readLength, err = connection.Read(message)

	// Check that read was successful.
	if err != nil {
		glog.Errorln("[protocol] Error receiving authentication response from" +
			"the backend.")
		glog.Errorf("[protocol] %s\n", err.Error())
	}

	glog.V(2).Infof("[protocol] %d bytes received from the backend.\n",
		readLength)

	return isAuthenticationOk(message)
}

/*
 * Check an Authentication Message to determine if it is an AuthenticationOK
 * message.
 */
func isAuthenticationOk(message []byte) bool {
	/*
	 * If the message type is not an Authentication message, then short circuit
	 * and return false.
	 */
	if getMessageType(message) != AUTHENTICATION_MESSAGE_TYPE {
		return false
	}

	var messageValue int32

	// Get the message length.
	messageLength := getMessageLength(message)

	// Get the message value.
	reader := bytes.NewReader(message[5:9])
	binary.Read(reader, binary.BigEndian, &messageValue)

	return (messageLength == 8 && messageValue == 0)
}

/*
 * Get the message type the provided message.
 *
 * message - the message
 */
func getMessageType(message []byte) byte {
	return message[0]
}

/*
 * Get the message length of the provided message.
 *
 * message - the message
 */
func getMessageLength(message []byte) int32 {
	var messageLength int32

	reader := bytes.NewReader(message[1:5])
	binary.Read(reader, binary.BigEndian, &messageLength)

	return messageLength
}

func ErrorResponse(buf []byte) {
	var msgLen int32

	reader := bytes.NewReader(buf[1:5])
	binary.Read(reader, binary.BigEndian, &msgLen)

	glog.V(2).Infof("[protocol] ErrorResponse: msglen=%d\n", msgLen)
	var errorMessage = string(buf[5:msgLen])
	glog.V(2).Infof("[protocol] ErrorResponse: message=%s\n", errorMessage)
}

func StartupRequest(buf []byte, bufLen int) {
	var msgLen int32
	var startupProtocol int32

	reader := bytes.NewReader(buf[0:4])
	binary.Read(reader, binary.BigEndian, &msgLen)

	reader.Reset(buf[4:8])
	binary.Read(reader, binary.BigEndian, &startupProtocol)

	glog.V(2).Infof("[protocol] StartupRequest: msglen=%d protocol=%d\n",
		msgLen, startupProtocol)
}

func QueryRequest(buf []byte) {
	var msgLen int32
	var query string

	reader := bytes.NewReader(buf[1:5])
	binary.Read(reader, binary.BigEndian, &msgLen)

	query = string(buf[5:msgLen])

	glog.V(2).Infof("[protocol] QueryRequest: msglen=%d query=%s\n", msgLen,
		query)
}

func NoticeResponse(buf []byte) {
	var msgLen int32

	reader := bytes.NewReader(buf[1:5])
	binary.Read(reader, binary.BigEndian, &msgLen)

	var fieldType = buf[5]
	var fieldMsg = string(buf[6:msgLen])

	glog.V(2).Infof("[protocol] NoticeResponse: msglen=%d fieldType=%x fieldMsg=%s\n",
		msgLen, fieldType, fieldMsg)
}

func RowDescription(buf []byte, bufLen int) {
	var msgLen int32

	reader := bytes.NewReader(buf[1:5])
	binary.Read(reader, binary.BigEndian, &msgLen)

	glog.V(2).Infof("[protocol] RowDescription: msglen=%d\n", msgLen)
	var data []byte

	data = buf[4+msgLen : bufLen]

	var dataRowType = string(data[0])
	glog.V(2).Infof("[protocol] datarow type%s found \n", dataRowType)

}

func DataRow(buf []byte) {
	var numFields int
	var msgLen int32
	var fieldLen int32
	var fieldValue string

	reader := bytes.NewReader(buf[1:5])
	binary.Read(reader, binary.BigEndian, &msgLen)

	reader.Reset(buf[5:7])
	binary.Read(reader, binary.BigEndian, &numFields)

	reader.Reset(buf[7:11])
	binary.Read(reader, binary.BigEndian, &fieldLen)

	fieldValue = string(buf[11 : fieldLen+11])

	glog.V(2).Infof("[protocol] DataRow: numfields=%d msglen=%d fieldLen=%d fieldValue=%s\n",
		numFields, msgLen, fieldLen, fieldValue)
}

func CommandComplete(buf []byte) {
	var msgLen int32

	buffer := bytes.NewReader(buf[1:5])
	binary.Read(buffer, binary.BigEndian, &msgLen)

	glog.V(2).Infof("[protocol] Command Complete: msglen=%d\n", msgLen)
}

func TerminateMessage(buf []byte) {
	var msgLen int32
	buffer := bytes.NewReader(buf[1:5])
	binary.Read(buffer, binary.BigEndian, &msgLen)
	glog.V(2).Infof("[protocol] Terminate: msglen=%d\n", msgLen)
}

func GetTerminateMessage() []byte {
	var buffer []byte
	buffer = append(buffer, 'X')

	//make msg len 1 for now
	x := make([]byte, 4)
	binary.BigEndian.PutUint32(x, uint32(4))
	buffer = append(buffer, x...)
	return buffer
}

/*
 * Create an SSL startup request message.
 */
/*func sslRequest() []byte {
	var buffer []byte

	messageLength := make([]byte, 4)
	sslRequestCode := make([]byte, 4)

	binary.BigEndian.PutUint32(messageLength, uint32(8))
	buffer = append(buffer, messageLength...)

	binary.BigEndian.PutUint32(sslRequestCode, uint32(SSL_REQUEST_CODE))
	buffer = append(buffer, sslRequestCode...)

	return buffer
}*/

/*
 * Authenticate a connection.
 *
 * connection - the connection to authenticate against.
 */
func Authenticate(connection net.Conn) bool {
	var readLength, writeLength int
	var err error
	var responseMessage []byte

	// Create the startup message.
	startupMessage := createStartupMessage()

	// Send the startup message to the backend.
	writeLength, err = connection.Write(startupMessage)

	if err == nil {
		glog.V(2).Infoln("[protocol] Startup message successfully sent to the backend.")
		glog.V(2).Infof("[protocol] %d bytes written to the backend.\n", writeLength)
	} else {
		glog.Errorf("[protocol] An error occurred sending the startup message: "+
			"%s\n", err.Error())
	}

	// Receive startup reponse from the backend.
	responseMessage = make([]byte, 2048)
	readLength, err = connection.Read(responseMessage)

	if err == nil {
		glog.V(2).Infoln("[protocol] Startup response message successfully " +
			"received from the backend.")
		glog.V(2).Infof("[protocol] %d bytes received from the backend.\n", readLength)
	} else {
		glog.Errorf("[protocol] An error occurred receiving the startup response: %s\n", err.Error())
	}

	/*
	 * Check the message type.
	 *
	 * The first byte of the message is always the message type. The received
	 * message should be an authentication type which has a value of 'R'.
	 */
	if responseMessage[0] != AUTHENTICATION_MESSAGE_TYPE {
		glog.Errorf("[protocol] Received incorrect message type: should "+
			"receive a authentication message type (%s), received (%s).\n",
			string(AUTHENTICATION_MESSAGE_TYPE),
			string(responseMessage[0]))
	}

	// Handle authentication request.
	authenticated := handleAuthenticationRequest(connection, responseMessage)

	if !authenticated {
		glog.Errorln("[protocol] Authentication failed.")
	}

	return authenticated
}

/*
 * Create a PG startup message. This message is used to startup all connections
 * with a PG backend.
 */
func createStartupMessage() []byte {

	//send startup packet
	var buffer []byte

	x := make([]byte, 4)

	// Temporarily set the message length to 0.
	binary.BigEndian.PutUint32(x, uint32(1))
	buffer = append(buffer, x...)

	// Set the protocol version.
	binary.BigEndian.PutUint32(x, uint32(PROTOCOL_VERSION))
	buffer = append(buffer, x...)

	/*
	 * The protocol version number is followed by one or more pairs of
	 * parameter name and value strings. A zero byte is required as a
	 * terminator after the last name/value pair. Parameters can appear in any
	 * order. 'user' is required, others are optional.
	 */
	var key, value string

	/*
	 * Set the 'user' parameter.  This is the only *required* parameter.
	 */
	key = "user"
	buffer = append(buffer, key...)
	buffer = append(buffer, 0)

	value = config.Cfg.Credentials.Username
	buffer = append(buffer, value...)
	buffer = append(buffer, 0)

	/*
	 * Set the 'database' parameter.  If no database name has been specified,
	 * then the default value is the user's name.
	 *
	 * TODO: Determine if the default should be handled here or if it assumed
	 * by the backend.
	 */
	key = "database"
	buffer = append(buffer, key...)
	buffer = append(buffer, 0)

	value = config.Cfg.Credentials.Database
	buffer = append(buffer, value...)
	buffer = append(buffer, 0)

	/*
	 * Set the 'client_encoding' parameter.
	 *
	 * TODO: Add this as a configuration specific item.
	 */
	key = "client_encoding"
	buffer = append(buffer, key...)
	buffer = append(buffer, 0)

	value = "UTF8"
	buffer = append(buffer, value...)
	buffer = append(buffer, 0)

	/*
	 * Set the 'datestyle' parameter.
	 */
	key = "datestyle"
	buffer = append(buffer, key...)
	buffer = append(buffer, 0)

	value = "ISO, MDY"
	buffer = append(buffer, value...)
	buffer = append(buffer, 0)

	/*
	 * Set the 'application_name' parameter.
	 */
	key = "application_name"
	buffer = append(buffer, key...)
	buffer = append(buffer, 0)

	value = "proxypool"
	buffer = append(buffer, value...)
	buffer = append(buffer, 0)

	/*
	 * Set the 'extra_float_digits' parameter.
	 */
	key = "extra_float_digits"
	buffer = append(buffer, key...)
	buffer = append(buffer, 0)

	value = "2"
	buffer = append(buffer, value...)
	buffer = append(buffer, 0)

	// TODO: Determine if this last null byte is necessary.
	buffer = append(buffer, 0)

	// update the msg len
	binary.BigEndian.PutUint32(buffer, uint32(len(buffer)))

	return buffer
}


text:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

import flask_admin as admin
from geoalchemy2.types import Geometry
from flask_admin.contrib.geoa import ModelView

# Create application
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)

class Point(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("POINT"))

class MultiPoint(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("MULTIPOINT"))

class Polygon(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("POLYGON"))

class MultiPolygon(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("MULTIPOLYGON"))

class LineString(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("LINESTRING"))

class MultiLineString(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    point = db.Column(Geometry("MULTILINESTRING"))

# Flask views
@app.route('/')
def index():
    return 'Click me to get to Admin!'

# Create admin
admin = admin.Admin(app, name='Example: GeoAlchemy', template_mode='bootstrap3')

# Add views
admin.add_view(ModelView(Point, db.session, category='Points'))
admin.add_view(ModelView(MultiPoint, db.session, category='Points'))
admin.add_view(ModelView(Polygon, db.session, category='Polygons'))
admin.add_view(ModelView(MultiPolygon, db.session, category='Polygons'))
admin.add_view(ModelView(LineString, db.session, category='Lines'))
admin.add_view(ModelView(MultiLineString, db.session, category='Lines'))

if __name__ == '__main__':

    db.create_all()

    # Start app
    app.run(debug=True)


text:
var memcached = require('./memcached');

// -------------------------------
// https://code.google.com/p/memcached/wiki/MemcacheBinaryProtocol
// 4.5. Increment
// -------------------------------

// set value
memcached.set('hello', 1, function(err, data) {
  if(err) {
    console.log('set error:', err);
    return;
  }

  console.log('set success:', data);
});

// increase value
memcached.increment('hello', 6, function(err, data) {
  if(err) {
    console.log('increment error:', err);
    return;
  }

  console.log('increment success:', data);
});

// get value
memcached.get('hello', function(err, data) {
  if(err) {
    console.log('get error:', err);
    return;
  }

  console.log('get success:', data);

  memcached.end();
});


text:
using SFML.Graphics;
using System.IO;

namespace SingleplayerEngine.Graphics.Sfml
{
    public class GraphicalSurface
    {
        public string Tag { private set; get; }
        public Sprite Sprite { private set; get; }

        public GraphicalSurface(string file) {
            // Does the file exist?
            if (File.Exists(file)) {
                // Set the tag to equal the file name without extension, and store the surface.
                var fi = new FileInfo(file);
                this.Tag = fi.Name.Remove(fi.Name.Length - fi.Extension.Length).ToLower();
                this.Sprite = new Sprite(new Texture(file));
            } else {
                throw new FileNotFoundException("GraphicalSurface: " + file);
            }
        }
    }
}


text:
import time
import sys
import datetime
import socket
import subprocess
import os
import configparser
import argparse
import sys

def is_weekend():
    now = datetime.datetime.now()
    return now.isoweekday() in range(6, 8)

def time_in_range(start, end):
    value = datetime.datetime.now().time()
    if start <= end:
        return start <= value <= end
    else:
        return start <= value or value <= end

def check_if_can_log(opts):  # Check if there are restrictions on place!

    if opts['start'] and opts['end'] and not time_in_range(opts['start'], opts['end']):
        return False

    if opts['skip_weekends'] and is_weekend():
        return False

    return True

def setup():
    """ Interactive setup routine for generating the conf-file. """
    opts = {}
    input('Generating configuration file for thymer. Leave selection blank to use the default settings.\n(Press ENTER to continue)')
    opts['THYME'] = input('\nInput path to the thyme executable. If thyme is defined in your path you can simply use "thyme" (default="~/workspace/bin/thyme")\n>')
    opts['DATA'] = input('\nInput path where you want to store thyme-logs (default="~/thyme_logs")\n>')
    opts['START'] = input('\nInput the time you want to start logging each day as HH:MM (default=always log)\n>')
    opts['END'] = input('\nInput the time you want to stop logging each day as HH:MM (default=always log)\n>')
    opts['INTERVAL'] = input('\nInput polling interval in seconds (default=30)\n>')
    opts['SKIP_WEEKENDS'] = input('\nInput whether to skip data loggin on weekends (default=False)\n>').lower() == 'true'

    if not opts['THYME']:
        opts['THYME'] = '~/workspace/bin/thyme'
    if not opts['DATA']:
        opts['DATA'] = '~/thyme_logs/'
    if not opts['START']:
        opts.pop('START', None)
    if not opts['END']:
        opts.pop('END', None)
    if not opts['INTERVAL']:
        opts['INTERVAL'] = 30.0
    else:
        opts['INTERVAL'] = float(opts['INTERVAL'])

    print('Writing configuration to ~/.config/pythymer.conf. If you want to change options in the future you can edit this file.')

    config = configparser.ConfigParser()
    config['SETUP'] = opts
    filename = os.path.expanduser('~') + '/.config/pythymer.conf'
    with open(filename, 'w+') as configfile:  # Check if we need to expand ~
        config.write(configfile)

    sys.exit('Thymer setup complete')

def read_configuration(config_file='~/.config/pythymer.conf'):
    """ Reads the predefined configurations. """

    config_file = config_file.replace('~', os.path.expanduser('~'))

    opts = {'thyme': '~/workspace/bin/thyme',
            'data': '~/thyme_logs/',
            'start': None,
            'end': None,
            'skip_weekends': False,
            'interval': 30.0}

    if os.path.isfile(config_file):

        config = configparser.ConfigParser()
        config.read(config_file)
        config = dict(config['SETUP'])

        if 'thyme' in config:
            opts['thyme'] = config['thyme']

        if 'data' in config:
            opts['data'] = config['data']

        if 'start' in config:
            opts['start'] = datetime.datetime.strptime(config['start'], '%H:%M').time()

        if 'end' in config:
            opts['end'] = datetime.datetime.strptime(config['end'], '%H:%M').time()

        if 'skip_weekends' in config:
            opts['skip_weekends'] = config['skip_weekends'].lower() == 'true'
    else:
        print('Warning: Can not find {}'.format(config_file))
        print('Using default parameter values.')

    opts['thyme'] = opts['thyme'].replace('~', os.path.expanduser('~'))
    opts['data'] = opts['data'].replace('~', os.path.expanduser('~'))

    return opts

def generate_filename():
    """ Generate filename for this day """
    return '{}.json'.format(str(datetime.date.today()))

def check_if_thyme_running():
    """ Checks if there is an existing thyme instance. """

    # TODO: Lock only works for linux for now
    if sys.platform == 'linux':
        global lock_socket
        lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        try:
            lock_socket.bind('\0' + 'pythymer.lock')
        except socket.error:
            sys.exit('An instance of pythymer is already running.')

def start_thymer():
    parser = argparse.ArgumentParser()
    parser.add_argument('--setup', help='Run the interactive setup', action='store_true')
    args = parser.parse_args()

    if args.setup:
        setup()

    check_if_thyme_running()
    opts = read_configuration()

    while True:
        filename = opts['data'] + generate_filename()
        if check_if_can_log(opts):
            subprocess.call([opts['thyme'], 'track', '-o', filename], shell=False)
        time.sleep(opts['interval'])

if __name__ == '__main__':
    start_thymer()


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

<title>ComputableWorkerImpl</title>
<meta name="date" content="2014-04-05">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deeplearning4j.scaleout.iterativereduce.multi.gradient

Class ComputableWorkerImpl

java.lang.Object

org.deeplearning4j.scaleout.iterativereduce.multi.gradient.ComputableWorkerImpl

All Implemented Interfaces:

ComputableWorker<UpdateableGradientImpl>

Direct Known Subclasses:

ComputableWorkerAkka

public abstract class ComputableWorkerImpl
extends java.lang.Object
implements ComputableWorker<UpdateableGradientImpl>

Worker for handling  subrows of a given set of matrix tasks.
 Compute cycles are left to the user.

Field Summary

Fields

Modifier and Type
Field and Description

protected UpdateableGradientImpl
workerResult

Constructor Summary

Constructors

Constructor and Description

ComputableWorkerImpl()

Method Summary

Methods

Modifier and Type
Method and Description

UpdateableGradientImpl
getResults()

void
update(UpdateableGradientImpl t)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface org.deeplearning4j.scaleout.iterativereduce.ComputableWorker

compute, compute, incrementIteration, setup

Field Detail

workerResult

protected UpdateableGradientImpl workerResult

Constructor Detail

ComputableWorkerImpl

public ComputableWorkerImpl()

Method Detail

getResults

public UpdateableGradientImpl getResults()

Specified by:

getResults in interface ComputableWorker<UpdateableGradientImpl>

update

public void update(UpdateableGradientImpl t)

Specified by:

update in interface ComputableWorker<UpdateableGradientImpl>

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
"""Offer MQTT listening automation rules."""
import json

import voluptuous as vol

from homeassistant.core import callback
from homeassistant.components import mqtt
from homeassistant.const import (CONF_PLATFORM, CONF_PAYLOAD)
import homeassistant.helpers.config_validation as cv

DEPENDENCIES = ['mqtt']

CONF_ENCODING = 'encoding'
CONF_TOPIC = 'topic'
DEFAULT_ENCODING = 'utf-8'

TRIGGER_SCHEMA = vol.Schema({
    vol.Required(CONF_PLATFORM): mqtt.DOMAIN,
    vol.Required(CONF_TOPIC): mqtt.valid_subscribe_topic,
    vol.Optional(CONF_PAYLOAD): cv.string,
    vol.Optional(CONF_ENCODING, default=DEFAULT_ENCODING): cv.string,
})

async def async_trigger(hass, config, action, automation_info):
    """Listen for state changes based on configuration."""
    topic = config[CONF_TOPIC]
    payload = config.get(CONF_PAYLOAD)
    encoding = config[CONF_ENCODING] or None

    @callback
    def mqtt_automation_listener(msg_topic, msg_payload, qos):
        """Listen for MQTT messages."""
        if payload is None or payload == msg_payload:
            data = {
                'platform': 'mqtt',
                'topic': msg_topic,
                'payload': msg_payload,
                'qos': qos,
            }

            try:
                data['payload_json'] = json.loads(msg_payload)
            except ValueError:
                pass

            hass.async_run_job(action, {
                'trigger': data
            })

    remove = await mqtt.async_subscribe(
        hass, topic, mqtt_automation_listener, encoding=encoding)
    return remove


text:
package de.ust.skill.common.java.internal.parts;

/**
 * A chunk that is used iff a field is appended to a preexisting type in a
 * block.
 *
 * @author Timm Felden
 */
public class BulkChunk extends Chunk {

    /**
     * number of blocks represented by this chunk
     */
    public final int blockCount;

    public BulkChunk(long begin, long end, long count, int blockCount) {
        super(begin, end, count);
        this.blockCount = blockCount;
    }

}


text:
require 'spec_helper'

describe Github::Client::Repos::Downloads, '#list' do
  let(:user) { 'peter-murach' }
  let(:repo) { 'github' }
  let(:request_path) { "/repos/#{user}/#{repo}/downloads" }

  before {
    stub_get(request_path).
      to_return(:body => body, :status => status,
        :headers => {:content_type => "application/json; charset=utf-8"})
  }

  after { reset_authentication_for(subject) }

  context "resource found" do
    let(:body)   { fixture('repos/downloads.json') }
    let(:status) { 200 }

    it { is_expected.to respond_to :all }

    it { expect { subject.list }.to raise_error(ArgumentError) }

    it "should fail to get resource without username" do
      expect { subject.list user }.to raise_error(ArgumentError)
    end

    it "should get the resources" do
      subject.list user, repo
      expect(a_get(request_path)).to have_been_made
    end

    it_should_behave_like 'an array of resources' do
      let(:requestable) { subject.list user, repo }
    end

    it "should get download information" do
      downloads = subject.list user, repo
      expect(downloads.first.name).to eq 'new_file.jpg'
    end

    it "should yield to a block" do
      yielded = []
      result = subject.list(user, repo) { |obj| yielded << obj }
      expect(yielded).to eq result
    end
  end

  it_should_behave_like 'request failure' do
    let(:requestable) { subject.list user, repo }
  end
end # list


text:
namespace $rootnamespace$
{

    internal partial class $safeitemname$
    {
        private static System.Resources.ResourceManager manager;
        internal static System.Resources.ResourceManager ResourceManager
        {
            get
            {
                if (($safeitemname$.manager == null))
                {
                    $safeitemname$.manager = new System.Resources.ResourceManager("$rootnamespace$.$safeitemname$", typeof($safeitemname$).Assembly);
                }
                return $safeitemname$.manager;
            }
        }
    }
}


text:
$: << File.expand_path("..", __FILE__)
require 'jruby_boot'
require 'irb'

c = Sonar::Connector::Controller.new File.join(CONNECTOR_ROOT, 'config', 'config.json')
c.start_console
IRB.start


text:
//
//  RegisterLastViewController.m
//  iSmartHome
//
//  Created by zwwang on 15/10/26.
//  Copyright © 2015年 zwwang. All rights reserved.
//

#import "RegisterLastViewController.h"
#import "AppDelegate.h"

@interface RegisterLastViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userName;

@property (weak, nonatomic) IBOutlet UITextField *code1;

@property (weak, nonatomic) IBOutlet UITextField *code2;

@end

@implementation RegisterLastViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)registerLandingAccount:(UIButton *)sender
{
    NSError __autoreleasing *error;

    AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];

    appDelegate.registerUser.userName = self.userName.text;

    if (self.code1.text ==  self.code2.text)
    {
        appDelegate.registerUser.password = self.code1.text;
    }

    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context];

    User *newUser = (User *)newManagedObject;
//    newUser.name = appDelegate.registerUser.name;
    newUser.password = appDelegate.registerUser.password ;
    newUser.sex =appDelegate.registerUser.sex ;
    newUser.birthday =appDelegate.registerUser.birthday ;
    newUser.height = appDelegate.registerUser.height;
    newUser.weight = appDelegate.registerUser.weight ;
    newUser.userName = appDelegate.registerUser.userName ;

    BOOL success;

    if (!(success = [context save:&error]))
    {
        NSLog(@"Unresolved error %@, %@",error, [error userInfo]);
        abort();
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
use strict;

use EnsEMBL::Web::DBHub;
use EnsEMBL::Web::Root;
use EnsEMBL::Web::DBSQL::WebsiteAdaptor;

my $hub          = EnsEMBL::Web::DBHub->new;
my $SD           = $hub->species_defs;
my $release_id   = $SD->ENSEMBL_VERSION;
my $species_name = $ENV{'ENSEMBL_SPECIES'};
my $helpdesk     = $SD->ENSEMBL_HELPDESK_EMAIL;
my $webmaster    = $SD->ENSEMBL_SERVERADMIN;
my $url          = $SD->ENSEMBL_BASEURL;

my $adaptor = EnsEMBL::Web::DBSQL::WebsiteAdaptor->new($hub);

my @all_species = $adaptor->fetch_all_species;
my $species_hash;

foreach my $sp (@all_species) {
  $species_hash->{$sp->{'name'}} = $sp->{'id'};
}

my $species      = { reverse %$species_hash };
my $pars         = { 'release' => $release_id };
my $species_id   = $species->{$species_name};

$pars->{ 'species' } = $species_id if $species_id;

my $this_species = $species_name || 'common';

my $criteria = {'release' => $release_id};
if ($species_id) {
  $criteria->{'species'} = $this_species;
}

my @news = @{$adaptor->fetch_news($criteria)};

print "Content-type: xml/rss\n\n";

print qq(
<rss version="2.0">
  <channel>
    <language>en</language>
    <category>Bioinformatics</category>
    <category>Genomics</category>
    <category>Genome Browsers</category>
    <copyright>Copyright 2008 The Ensembl webteam</copyright>
    <managingEditor>$helpdesk</managingEditor>
    <webMaster>$webmaster</webMaster>
    <title>Ensembl release $release_id</title>
    <link>$url</link>
    <generator>Ensembl web API</generator>
    <image>
      <url>$url/img/e-rss.png</url>
      <title>Ensembl release $release_id</title>
      <link>$url</link>
    </image>
    <ttl>1440</ttl>
    <description>
      Ensembl is a joint project between EMBL-EBI and the Sanger Institute
      to develop a software system which produces and maintains automatic
      annotation on selected eukaryotic genomes. Ensembl is primarily
      funded by the Wellcome Trust. The site provides free access to all
      the data and software from the Ensembl project. Click on a species
      name to browse the data.
    </description>
    <language>en-gb</language>
);

foreach my $item ( @news ) {
  my $C = EnsEMBL::Web::Root::strip_HTML($item->{'content'});
  printf '
    <item>
      <title>%s</title>
      <description>%s</description>
      <link>%s/info/website/news/index.html#news_%s</link>
    </item>',
    $item->{'title'}, $C, $url, $item->{'id'};
}
print qq(
  </channel>
</rss>);

1;


text:
<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class SuggestedMission extends Model{

    use SoftDeletes;

    protected $table = 'suggested_missions';

    protected $fillable = ['description', 'user_id'];

    public function user(){
        return $this->belongsTo('App\Models\User');
    }

}


text:
export FLASK_APP=hello.py
export FLASK_ENV=development
flask run


text:
//// --------------------------------------------------------------------------------------------------------------------
//// <copyright file="IDeviceInterfaceDetails.cs" company="None.">
////   TODO:
//// </copyright>
//// <summary>
////   The DeviceInterfaceDetails interface.
//// </summary>
//// --------------------------------------------------------------------------------------------------------------------

//namespace WinUsbRx.UnsafeNative
//{
//    using DeviceProperties;

//    /// <summary>
//    /// The DeviceInterfaceDetails interface.
//    /// </summary>
//    internal interface IDeviceInterfaceDetails
//    {
//        /// <summary>
//        /// Gets the manufacturer.
//        /// </summary>
//        BaseDeviceProperty Manufacturer { get; }

//        /// <summary>
//        /// Gets the device description.
//        /// </summary>
//        BaseDeviceProperty DeviceDescription { get; }

//        /// <summary>
//        /// Gets the path name.
//        /// </summary>
//        string PathName { get; }
//    }
//}


text:
namespace SIM.Client.Commands
{
  using CommandLine;
  using Sitecore.Diagnostics.Base.Annotations;
  using SIM.Core.Commands;

  public class ProfileCommandFacade : ProfileCommand
  {
    [UsedImplicitly]
    public ProfileCommandFacade()
    {
    }

    [Option('c', "connectionString")]
    public override string ConnectionString { get; set; }

    [Option('i', "instancesRoot")]
    public override string InstancesRoot { get; set; }

    [Option('l', "license")]
    public override string License { get; set; }

    [Option('r', "repository")]
    public override string Repository { get; set; }
  }
}


text:
using System;
using MonoMac.Foundation;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac.CoreGraphics;

namespace MonoMac.CoreAnimation {

	partial class CAAnimation {
		const string Linear = "linear";
		const string Discrete = "discrete";
		const string Paced = "paced";
		const string Cubic = "cubic";

		const string RotateAuto = "auto";
		const string RotateAutoReverse = "autoReverse";

		[DllImport(Constants.QuartzLibrary, EntryPoint="CACurrentMediaTime")]
		public extern static double CurrentMediaTime ();
	}

	public partial class CAFillMode {
		public const string Removed = "removed";
		public const string Forwards = "forwards";
		public const string Backwards = "backwards";
		public const string Both = "both";
		public const string Frozen = "frozen";
	}

	partial class CATransition {
		const string Fade = "fade";
		const string MoveIn = "moveIn";
		const string Push = "push";
		const string Reveal = "reveal";

		const string FromRight = "fromRight";
		const string FromLeft = "fromLeft";
		const string FromTop = "fromTop";
		const string FromBottom = "fromBottom";
	}

	public partial class CAGradientLayer {
		public CGColor CreateColor (IntPtr p)
		{
			return new CGColor (p);
		}

		public CGColor [] Colors {
			get {
				return NSArray.ArrayFromHandle<CGColor> (_Colors, CreateColor);
			}

			set {
				if (value == null)
					throw new ArgumentNullException ("value");

				IntPtr [] ptrs = new IntPtr [value.Length];
				for (int i = 0; i < ptrs.Length; i++)
					ptrs [i] = value [i].Handle;

				using (NSArray array = NSArray.FromIntPtrs (ptrs)){
					_Colors = array.Handle;
				}
			}
		}
	}

	[StructLayout (LayoutKind.Sequential)]
	public struct CABarBeatTime {
		public int Bar;
		public ushort Beat;
		public ushort Subbeat;
		public ushort SubbeatDivisor;
		public ushort Reserved;
	}

}