text:
package org.kuali.kfs.fp.document.web.struts;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.kuali.kfs.fp.businessobject.AdvanceDepositDetail;
import org.kuali.kfs.fp.document.AdvanceDepositDocument;
import org.kuali.kfs.fp.document.validation.impl.AdvanceDepositDocumentRuleUtil;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.krad.util.GlobalVariables;

/**
 * This is the action class for the Advance Deposit document.
 */
public class AdvanceDepositAction extends CapitalAccountingLinesActionBase {

    /**
     * Adds handling for advance deposit detail amount updates.
     *
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm,
     *      javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        AdvanceDepositForm adForm = (AdvanceDepositForm) form;

        if ( adForm != null && adForm.hasDocumentId()) {
            AdvanceDepositDocument adDoc = adForm.getAdvanceDepositDocument();

            adDoc.setTotalAdvanceDepositAmount(calculateAdvanceDepositTotal(adDoc)); // recalc b/c changes to the amounts could
            // have happened
        }

        // proceed as usual
        return super.execute(mapping, form, request, response);
    }

    /* NOTE
     * The following method was originally added to fix the NPE caused by the reference to AdvanceDepositDocument inside AdvanceDepositDetail.
     * Now it's commented out as we are fixing the NPE in a better way, by removing the nested reference to AdvanceDepositDocument,
     * which is not used anymore.
     */
    /**
     * Overridden to ensure that the nested AdvanceDepositDocuments in AdvanceDepositDetails are populated.
     * @see org.kuali.rice.kns.web.struts.action.KualiTransactionalDocumentActionBase#copy(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     *
    @Override
    public ActionForward copy(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        AdvanceDepositForm adForm = (AdvanceDepositForm) form;
        AdvanceDepositDocument adDoc = adForm.getAdvanceDepositDocument();
        List<AdvanceDepositDetail> advanceDeposits = adDoc.getAdvanceDeposits();

        for (AdvanceDepositDetail advanceDeposit: advanceDeposits) {
            /* somehow ObjectUtils.isNull(nestAdDoc) returns false here
            AdvanceDepositDocument nestAdDoc = advanceDeposit.getAdvanceDepositDocument();
            if (ObjectUtils.isNull(nestAdDoc)) {
                nestAdDoc = null;
            }
            *
            // need to populate the referred document, otherwise there will be NPE when copying
            advanceDeposit.setAdvanceDepositDocument(adDoc);
        }
        return super.copy(mapping, form, request, response);
    }
    */

    /**
     * Adds a AdvanceDepositDetail instance created from the current "new advanceDeposit" line to the document
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward addAdvanceDeposit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        AdvanceDepositForm adForm = (AdvanceDepositForm) form;
        AdvanceDepositDocument adDoc = adForm.getAdvanceDepositDocument();

        AdvanceDepositDetail newAdvanceDeposit = adForm.getNewAdvanceDeposit();
        adDoc.prepareNewAdvanceDeposit(newAdvanceDeposit);

        // advanceDeposit business rules
        boolean rulePassed = validateNewAdvanceDeposit(newAdvanceDeposit);
        if (rulePassed) {
            // add advanceDeposit
            adDoc.addAdvanceDeposit(newAdvanceDeposit);

            // clear the used advanceDeposit
            AdvanceDepositDetail advanceDepositDetail = new AdvanceDepositDetail();
            advanceDepositDetail.setDefaultBankCode();
            adForm.setNewAdvanceDeposit(advanceDepositDetail);
        }

        return mapping.findForward(KFSConstants.MAPPING_BASIC);
    }

    /**
     * Deletes the selected advanceDeposit (line) from the document
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward deleteAdvanceDeposit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        AdvanceDepositForm adForm = (AdvanceDepositForm) form;
        AdvanceDepositDocument adDoc = adForm.getAdvanceDepositDocument();

        int deleteIndex = getLineToDelete(request);
        // delete advanceDeposit
        adDoc.removeAdvanceDeposit(deleteIndex);

        return mapping.findForward(KFSConstants.MAPPING_BASIC);
    }

    /**
     * This method validates a new advance deposit detail record.
     *
     * @param advanceDeposit
     * @return boolean
     */
    protected boolean validateNewAdvanceDeposit(AdvanceDepositDetail advanceDeposit) {
        GlobalVariables.getMessageMap().addToErrorPath(KFSPropertyConstants.NEW_ADVANCE_DEPOSIT);
        boolean isValid = AdvanceDepositDocumentRuleUtil.validateAdvanceDeposit(advanceDeposit);
        GlobalVariables.getMessageMap().removeFromErrorPath(KFSPropertyConstants.NEW_ADVANCE_DEPOSIT);
        return isValid;
    }

    /**
     * Recalculates the advance deposit total since user could have changed it during their update.
     *
     * @param advanceDepositDocument
     */
    protected KualiDecimal calculateAdvanceDepositTotal(AdvanceDepositDocument advanceDepositDocument) {
        KualiDecimal total = KualiDecimal.ZERO;
        Iterator<AdvanceDepositDetail> deposits = advanceDepositDocument.getAdvanceDeposits().iterator();
        while (deposits.hasNext()) {
            AdvanceDepositDetail deposit = deposits.next();
            if (deposit.getFinancialDocumentAdvanceDepositAmount() !=null) {
            total = total.add(deposit.getFinancialDocumentAdvanceDepositAmount());
            }
        }
        return total;
    }
}


text:
$(document).ready(function(){
  if($("#map_canvas").length > 0){
    configure_map();
  }
});

function configure_map(){
  var cartodb_table_name = $("#map_canvas").data("cartodb-table-name");
  var cartodb_username = $("#map_canvas").data("cartodb-username");

  var map = new L.Map('map_canvas', {
    center: [0,0],
    zoom: 2
  });

  // Add layer with basemap
  L.tileLayer('http://{s}.api.cartocdn.com/base-light/{z}/{x}/{y}.png', {
    attribution: 'cartoDB'
  }).addTo(map);

 // Add layer with data
  cartodb.createLayer(map, {
    user_name: cartodb_username,
    type: 'cartodb',
    infowindow: true,
    sublayers: [{
      sql: "SELECT * FROM " + cartodb_table_name,
      cartocss: "\
        #rails_rails_contributors { \
          marker-fill-opacity: 0.8; \
          marker-line-color: #555; \
          marker-line-width: 1; \
          marker-line-opacity: 1; \
          marker-placement: point; \
          marker-multi-policy: largest; \
          marker-type: ellipse; \
          marker-fill: #48cfad; \
          marker-allow-overlap: true; \
          marker-clip: false;  \
        } \
        #rails_rails_contributors { \
          marker-width: 10; \
        }"
    }]
  }).addTo(map)
  .done(function(layer) {
    cdb.vis.Vis.addInfowindow(map, layer.getSubLayer(0), ['username', 'location', 'contributions'])
  });
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.michaelfredeickson.progressivemetronome.practicesection;

import com.github.michaelfredeickson.progressivemetronome.MetronomeActivity;

import java.io.Serializable;

public class PracticeSectionController implements Serializable {

    private PracticeSectionActivity IncrementorActivity;
    private PracticeSectionMetronome incrementMetronome;
    private MetronomeActivity metronomeActivity;
//    private SoundGenerator soundGenerator;
//    private ParseMetronome parseMetronome;

    public PracticeSectionController(PracticeSectionActivity IncrementorActivity) {
        this.IncrementorActivity = IncrementorActivity;
        incrementMetronome = new PracticeSectionMetronome();

    }

    public PracticeSectionController(MetronomeActivity MetronomeActivity){

        this.metronomeActivity = MetronomeActivity;
        incrementMetronome = new PracticeSectionMetronome();

    }

    public int getStartingTempo() {
        return incrementMetronome.getStartingTempo();
    }

    public void setStartingTempo(int tempo) {
        incrementMetronome.setStartingTempo(tempo);
    }

    public int getEndingTempo() {
        return incrementMetronome.getEndingTempo();
    }

    public void setEndingTempo(int tempo) {
        incrementMetronome.setEndingTempo(tempo);
    }

    public int passageLength() { return 4; }

    public void startMetronome() {

//        if (soundGenerator != null) {
//            soundGenerator.stop();
//        }
//        soundGenerator = new SoundGenerator(incrementMetronome.getStartingTempo(), incrementMetronome.getNumBeatsInMeasure(), incrementMetronome.getBeep(), incrementMetronome.getFirstBeep());

//        parseMetronome = new ParseMetronome(incrementMetronome.getStartingTempo(), incrementMetronome.getEndingTempo(), incrementMetronome.getNumBeatsInMeasure(), incrementMetronome.getPassageLength(), incrementMetronome.getIncrease(), incrementMetronome.getRepetitions(), incrementorMetronome.getCountdown());
//        parseMetronome.Countdown();

    }

    public void stopMetronome() {
//        if (soundGenerator != null) {
//            soundGenerator.stop();
//        }

    }

//    public void upMeasure() {
//        incrementMetronome.upNumBeatsInMeasure();
//        IncrementorActivity.updateMeasureView(incrementMetronome.getNumBeatsInMeasure());
//
//    }
//
//    public void downMeasure() {
//        incrementMetronome.downNumBeatsInMeasure();
//        IncrementorActivity.updateMeasureView(incrementMetronome.getNumBeatsInMeasure());
//
//    }

    public void setNumMeasures(int numMeasures){

           incrementMetronome.setPassageLength(numMeasures);

    }

    public int getNumMeasures(){

        return incrementMetronome.getPassageLength();
    }

    public void setIncreaseAmount(int increase){

        incrementMetronome.setIncrease(increase);

    }

    public int getIncreaseAmount() {

    return incrementMetronome.getIncrease();}

    public void setRepetitionsAmount(int repetitions){

        incrementMetronome.setRepetitions(repetitions);

    }

    public int getRepetitionsAmount(){

        return incrementMetronome.getRepetitions();
    }

    public void setCountdown(int countdown){

        incrementMetronome.setCountdown(countdown);
    }

    public int getCountdown(){

        return incrementMetronome.getCountdown();

    }

    public int getNumBeatsInMeasure(){

        return incrementMetronome.getNumBeatsInMeasure();

    }

    public void setNumBeatsInMeasure(int numBeatsInMeasure){

        incrementMetronome.setNumBeatsInMeasure(numBeatsInMeasure);
    }

    public void setSubdivision(double subDivision){

        incrementMetronome.setSubDivision(subDivision);

    }

    public double getSubDivision(){

        return incrementMetronome.getSubDivision();
    }

    public void setAccent(int accent){

        incrementMetronome.setAccent(accent);

    }

    public int getAccent(){

        return incrementMetronome.getAccent();

    }

    public void setTimeSignatureNumerator(int timeSignatureNumerator){

        incrementMetronome.setTimeSignatureNumerator(timeSignatureNumerator);

    }

    public void setTimeSignatureDenominator(int timeSignatureDenominator){

        incrementMetronome.setTimeSignatureDenominator(timeSignatureDenominator);

    }

    public int getTimeSignatureNumerator(int timeSignatureNumerator){

       return incrementMetronome.getTimeSignatureNumerator();

    }

    public int getTimeSignatureDenominator(int timeSignatureDenominator){

       return incrementMetronome.getTimeSignatureDenominator();

    }

}


text:
/*
 * @(#)FullThreadDump.java	1.7 10/03/23
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Oracle or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

/*
 * @(#)FullThreadDump.java	1.7 10/03/23
 */

import javax.management.*;
import javax.management.remote.*;
import java.io.IOException;
import java.net.MalformedURLException;

/**
 * This FullThreadDump class demonstrates the capability to get
 * a full thread dump and also detect deadlock remotely.
 */
public class FullThreadDump {
    private MBeanServerConnection server;
    private JMXConnector jmxc;
    public FullThreadDump(String hostname, int port) {
        System.out.println("Connecting to " + hostname + ":" + port);

        // Create an RMI connector client and connect it to
        // the RMI connector server
        String urlPath = "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi";
        connect(urlPath);
   }

   public void dump() {
        try {
            ThreadMonitor monitor = new ThreadMonitor(server);
            monitor.threadDump();
            if (!monitor.findDeadlock()) {
                System.out.println("No deadlock found.");
            }
        } catch (IOException e) {
            System.err.println("\nCommunication error: " + e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Connect to a JMX agent of a given URL.
     */
    private void connect(String urlPath) {
        try {
            JMXServiceURL url = new JMXServiceURL("rmi", "", 0, urlPath);
            this.jmxc = JMXConnectorFactory.connect(url);
            this.server = jmxc.getMBeanServerConnection();
        } catch (MalformedURLException e) {
            // should not reach here
        } catch (IOException e) {
            System.err.println("\nCommunication error: " + e.getMessage());
            System.exit(1);
        }
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            usage();
        }

        String[] arg2 = args[0].split(":");
        if (arg2.length != 2) {
            usage();
        }
        String hostname = arg2[0];
        int port = -1;
        try {
            port = Integer.parseInt(arg2[1]);
        } catch (NumberFormatException x) {
            usage();
        }
        if (port < 0) {
            usage();
        }

        // get full thread dump and perform deadlock detection
        FullThreadDump ftd = new FullThreadDump(hostname, port);
        ftd.dump();
    }

    private static void usage() {
        System.out.println("Usage: java FullThreadDump <hostname>:<port>");
    }
}


text:
tags: perl
layout: post
title: "Hooking up with OpenThought"
---

I realize I'm probably tempting fate by releasing new
versions of both OpenInteract and
SPOPS at 2 in the morning. But so it goes: 1.3
(tons of cool stuff) and 0.50 (mostly bugfixes +
enhancements) are on the street.

Built a relatively small website the other day using
(gasp!) server-side includes. Refreshing to go back to the
extremely short iteration cycles of that type of
development, even though I have no patience for mucking with
HTML anymore.

Also connecting with the developer of OpenThought, another
Perl webapp server. But it approaches things very
differently from OpenInteract -- lots of Javascript as it
tries to be more of a traditional application. Interesting.

Thing is, he's got many of the same needs as all the
other 11 million webapp servers: authentication, data
abstraction, sessions.... And hey, why not create a layer
that works with everything? So we're hashing that out over
email right now. He came to my talk at YAPC in June
(and even got one of the t-shirts!). And he's not far away
(relatively: probably 3-4 hours driving), so it might be
cool as this thing progresses to get together
.

Still trying to think of a name for the project. I suck
at that.

(Originally posted elsewhere)


text:
define(function (require) {

    var React = require('react');
    var Method = require('./components/Method.jsx');
    var Code = require('./components/Code.jsx');

    return React.createClass({
        // @override
        getDefaultProps: function () {
            return {
                item: {}
            };
        },
        render: function () {
            var item = this.props.item;
            item.name = 'this.' + item.interface;
            return (

                    <Method item={item}/>
                    {item.note ?  : null}

            );
        }
    });
});


text:
===========
ALTER TABLE
===========

Synopsis
--------

.. code-block:: none

    ALTER TABLE [ IF EXISTS ] name RENAME TO new_name
    ALTER TABLE [ IF EXISTS ] name ADD COLUMN [ IF NOT EXISTS ] column_name data_type
      [ COMMENT comment ]
      [ WITH ( property_name = expression [, ...] ) ]
    ALTER TABLE [ IF EXISTS ] name DROP COLUMN [ IF EXISTS ] column_name
    ALTER TABLE [ IF EXISTS ] name RENAME COLUMN [ IF EXISTS ] column_name TO new_column_name

Description
-----------

Change the definition of an existing table.

The optional ``IF EXISTS`` (when used before the table name) clause causes the error to be suppressed if the table does not exists.

The optional ``IF EXISTS`` (when used before the column name) clause causes the error to be suppressed if the column does not exists.

The optional ``IF NOT EXISTS`` clause causes the error to be suppressed if the column already exists.

Examples
--------

Rename table ``users`` to ``people``::

    ALTER TABLE users RENAME TO people;

Rename table ``users`` to ``people`` if table ``users`` exists::

    ALTER TABLE IF EXISTS users RENAME TO people;

Add column ``zip`` to the ``users`` table::

    ALTER TABLE users ADD COLUMN zip varchar;

Add column ``zip`` to the ``users`` table if table ``users`` exists and column ``zip`` not already exists::

    ALTER TABLE IF EXISTS users ADD COLUMN IF NOT EXISTS zip varchar;

Drop column ``zip`` from the ``users`` table::

    ALTER TABLE users DROP COLUMN zip;

Drop column ``zip`` from the ``users`` table if table ``users`` and column ``zip`` exists::

    ALTER TABLE IF EXISTS users DROP COLUMN IF EXISTS zip;

Rename column ``id`` to ``user_id`` in the ``users`` table::

    ALTER TABLE users RENAME COLUMN id TO user_id;

Rename column ``id`` to ``user_id`` in the ``users`` table if table ``users`` and column ``id`` exists::

    ALTER TABLE IF EXISTS users RENAME column IF EXISTS id to user_id;

See Also
--------

:doc:`create-table`


text:
package me.wbprime.springdbusecase.springdatajpa.xml.controllers;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import me.wbprime.springdbusecase.springdatajpa.xml.dto.ErrorDTO;
import me.wbprime.springdbusecase.springdatajpa.xml.dto.PingDTO;
import me.wbprime.springdbusecase.springdatajpa.xml.exceptions.PingNotFoundException;
import me.wbprime.springdbusecase.springdatajpa.xml.services.PingServiceI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * Class: PingController
 * Date: 2016/04/18 21:29
 *
 * @author Elvis Wang [mail@wbprime.me]
 */
@RestController
public class PingController {
    private static Logger logger = LoggerFactory.getLogger(PingController.class);

    @Resource(name = "pingService")
    private PingServiceI pingService;

    @RequestMapping(value = "ping", method = RequestMethod.POST)
    public PingDTO add(@Valid @RequestBody final PingDTO dto) {
        final PingDTO result = pingService.insert(dto);
        return result;
    }

    @RequestMapping(value = "ping", method = RequestMethod.GET)
    public List<PingDTO> list() {
        return pingService.findAll();
    }

    @RequestMapping(value = "ping/{id}", method = RequestMethod.GET)
    public PingDTO get(@PathVariable("id") final int id) throws PingNotFoundException {
        final PingDTO result = pingService.findOne(id);
        return result;
    }

    @RequestMapping(value = "ping/{id}", method = RequestMethod.PUT)
    public PingDTO update(
        @PathVariable("id") final int id,
        @Valid @RequestBody final PingDTO dto
    ) throws PingNotFoundException {
        final PingDTO result = pingService.updateOne(id, dto);
        return result;
    }

    @RequestMapping(value = "ping/{id}", method = RequestMethod.DELETE)
    public PingDTO delete(@PathVariable("id") final int id) throws PingNotFoundException {
        final PingDTO result = pingService.deleteOne(id);
        return result;
    }

    @ExceptionHandler(PingNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public List<ErrorDTO> handlePingNotFoundException(final PingNotFoundException e) {
        final ErrorDTO dto = new ErrorDTO();
        dto.setError(e.getMessage());

        return ImmutableList.of(
            dto
        );
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public List<ErrorDTO> handleBindException(final MethodArgumentNotValidException e) {
        final BindingResult bindingResult = e.getBindingResult();
        final List<ErrorDTO> result =
            Lists.newArrayListWithExpectedSize(bindingResult.getErrorCount());
        for (FieldError error : bindingResult.getFieldErrors()) {
            final ErrorDTO dto = new ErrorDTO();
            dto.setError(error.getField() + ": " + error.getDefaultMessage());
            result.add(dto);
        }

        return result;
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public List<ErrorDTO> handleRuntimeException(final RuntimeException e) {
        final ErrorDTO dto = new ErrorDTO();
        dto.setError(e.getMessage());

        return ImmutableList.of(
            dto
        );
    }
}


text:
'use strict';

const suman = require('suman');
const {Test} = suman.init(module);
const su = require('suman-utils');

//////////////////////////////////////////////////////////////////////////

Test.create(['semver', function (b, assert, describe, before, beforeEach, after, afterEach, it) {

  before.cb('adds foo', h => {
     suman.run.cb({args: ['--default']}, function (err, v) {
      h.supply.v = v;
      h.done(err);
    });
  });

  it('sync test', t => {
    t.assert(su.isStream(t.supply.v.sumanProcess.stdout), 'stdout is not a stream.');
    t.assert(su.isStream(t.supply.v.sumanProcess.stderr), 'stderr is not defined');
  });

  describe.parallel('par', b => {

    it.parallel('sync test', t => {

      setTimeout(function () {
        t.supply.v.sumanProcess.stdout.pipe(process.stdout);
        t.supply.v.sumanProcess.stderr.pipe(process.stderr);
      }, 1000);

      // setTimeout(function () {
      //   t.supply.v.sumanProcess.stdout.pause();
      //   t.supply.v.sumanProcess.stderr.pause();
      // }, 200);

      // t.supply.v.sumanProcess.stdout.resume();
      // t.supply.v.sumanProcess.stderr.resume();
    });

    it.parallel.cb('wait for exit', t => {
      t.supply.v.sumanProcess.stdout.once('finish', t.pass);
    });

  });

}]);


text:
using namespace SDKTemplate;

using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Globalization;

Scenario1_Data::Scenario1_Data()
{
    InitializeComponent();
}

String^ Scenario1_Data::ReportCalendarData(Calendar^ calendar, String^ calendarLabel)
{
    String^ results = calendarLabel + ": " + calendar->GetCalendarSystem() + "\n";
    results += "Name of Month: " + calendar->MonthAsSoloString() + "\n";
    results += "Day of Month: " + calendar->DayAsPaddedString(2) + "\n";
    results += "Day of Week: " + calendar->DayOfWeekAsSoloString() + "\n";
    results += "Year: " + calendar->YearAsString() + "\n";
    results += "\n";
    return results;
}

void Scenario1_Data::ShowResults()
{
    // This scenario uses the Windows.Globalization.Calendar class to display the parts of a date.

    // Create Calendar objects using different constructors.
    Calendar^ calendar = ref new Calendar();
    Calendar^ japaneseCalendar = ref new Calendar(ref new Vector<String^>({ "ja-JP" }), CalendarIdentifiers::Japanese, ClockIdentifiers::TwelveHour);
    Calendar^ hebrewCalendar = ref new Calendar(ref new Vector<String^>({ "he-IL" }), CalendarIdentifiers::Hebrew, ClockIdentifiers::TwentyFourHour);

    // Display the results
    OutputTextBlock->Text =
        ReportCalendarData(calendar, "User's default calendar system") +
        ReportCalendarData(japaneseCalendar, "Calendar system") +
        ReportCalendarData(hebrewCalendar, "Calendar system");
}


text:
package steps;

import jsystem.framework.TestProperties;
import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Wait extends AbstractSeleniumBuilderTestCase {

	private String url;

	private String title;

	private int timeOutInSec = 60;

	private String text;

	private By by;

	private String locator;

	private WebDriverWait wait;

	@Before
	public void setUp() {
		wait = new WebDriverWait(driver, timeOutInSec);
	}

	/**
	 * Wait for URL
	 */
	@Test
	@TestProperties(name = "Wait for url ${url} for ${timeOutInSec} seconds", paramsInclude = { "url", "timeOutInSec" })
	public void waitForCurrentUrl() {

	}

	@Test
	@TestProperties(name = "Wait for title ${title} for ${timeOutInSec} seconds", paramsInclude = { "title",
			"timeOutInSec" })
	public void waitForTitle() {
		wait.until(ExpectedConditions.titleContains(title));
	}

	@Test
	@TestProperties(name = "Wait for text in element ${by}:${locator} to be '${text}' for ${timeOutInSec} seconds", paramsInclude = {
			"by", "locator", "text", "timeOutInSec" })
	public void waitForText() {
		WebElement element = findElement(by, locator);
		wait.until(ExpectedConditions.textToBePresentInElement(element, text));
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public int getTimeOutInSec() {
		return timeOutInSec;
	}

	public void setTimeOutInSec(int timeOutInSec) {
		this.timeOutInSec = timeOutInSec;
	}

}


text:
namespace ModTools.Scripting
{
    internal sealed class ScriptEditorFile
    {
        public const string DefaultSource = @"//You can copy this script's file and use it for your own scripts
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Linq;
using ColossalFramework.UI;
using UnityEngine;

namespace ModTools.Scripting
{
    class ExampleScript : IModEntryPoint
    {
        public void OnModLoaded()
        {
            throw new Exception(""Hello World!""); //replace this line with your script
        }
        public void OnModUnloaded()
        {
            throw new Exception(""Goodbye Cruel World!""); //replace this line with your clean up script
        }
    }
}";

        public ScriptEditorFile(string source, string path)
        {
            Source = source ?? string.Empty;
            Path = path ?? string.Empty;
        }

        public string Source { get; set; }

        public string Path { get; }
    }
}


text:
function Solve(args) {
    var input = parseInput(args);
    var firstRowLength = input[0].length;
    var rowsCount = input.length;
    var maxSpecialValue = 0;

    for (var index = 0; index < firstRowLength; index++) {
        var visitedNegative = false;
        var currentPath = 1;
        var nextCol = input[0][index];
        if (nextCol >= 0) {
            var visited = {};
            var nextRow = 0;
            do {
                visited[nextRow + " " + nextCol] = true;
                nextRow = (nextRow + 1) % rowsCount;
                currentPath++;
                if (input[nextRow][nextCol] < 0) {
                    visitedNegative = true;
                    currentPath += Math.abs(input[nextRow][nextCol]);
                    break;
                }
                nextCol = input[nextRow][nextCol];
            } while (!visited[nextRow + " " + nextCol]);
        }
        else {
            visitedNegative = true;
            currentPath += Math.abs(nextCol);
        }
        if (visitedNegative) {
            if (maxSpecialValue < currentPath) {
                maxSpecialValue = currentPath;
            }
        }
    }
    return maxSpecialValue;
}

function parseInput(args) {
    var n = parseInt(args[0]);
    var input = new Array(n);
    for (var i = 0; i < n; i++) {
        var currentElements = args[i + 1].split(", ");
        input[i] = new Array();
        for (var j = 0; j < currentElements.length; j++) {
            input[i][j] = parseInt(currentElements[j]);
        }
    }
    return input;
}


text: mysql project --user=root --password < /data/setup/mysql/functions.sql


text:
package org.factcast.example.client.basicauth;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SuppressWarnings("ALL")
@SpringBootApplication
public class ExampleClient {
    public static void main(String[] args) {
        SpringApplication.run(ExampleClient.class, args);
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace SampleApp_RDotNet_VS2012
{
    public class PIData_PIWA
    {
        private string baseUrl = "https://marc-web-sql.marc.net/piwebapi/";
        private IDictionary<string, string> PIServersWebIdDic;
        private string PIServerName = string.Empty;
        private string MyTagName1 = string.Empty;
        private string MyTagName2 = string.Empty;
        private string MyTagName3 = string.Empty;
        private string MyTagName4 = string.Empty;
        private string MyTagName5 = string.Empty;
        private dynamic MyTag1 = null;
        private dynamic MyTag2 = null;
        private dynamic MyTag3 = null;
        private dynamic MyTag4 = null;
        private dynamic MyTag5 = null;

        public PIData_PIWA()
        {

        }

        public string GetPIWAversion()
        {
            string VersionUrl = baseUrl + "/version";
            dynamic VersionResult = MakeRequest(VersionUrl).Result;
            return (VersionResult.FullVersion.Value);
        }

        public int ConnectToPIServer(string piservername, int def)
        {
            if (PIServersWebIdDic == null)
            {
                GetPIServersListWebId();
            }

            try
            {

                if (def == 0)
                {

                }
                else
                {
                    string[] PIServersList = GetPIServersList();
                    piservername = PIServersList[0];

                }
                string PIPointsUrl = PIServersWebIdDic[piservername];
                //dynamic PIPointsWebAPI = MakeRequest(PIPointsUrl).Result;

                PIServerName = piservername;
                return 1;
            }
            catch
            {
                return 0;
            }
        }

        private void GetPIServersListWebId()
        {
            string PIServersUrl = baseUrl + "dataservers";
            dynamic PIServersList = MakeRequest(PIServersUrl).Result;
            PIServersWebIdDic = null;
            PIServersWebIdDic = new Dictionary<string, string>();

            for (int i = 0; i < PIServersList.Items.Count; i++)
            {
                PIServersWebIdDic.Add(PIServersList.Items[i].Name.Value, PIServersList.Items[i].Links.Points.Value);
            }
        }

        public string[] GetPIServersList()
        {
            GetPIServersListWebId();
            List<string> sPIServersList = new List<string>();
            foreach(var PIServer in PIServersWebIdDic)
            {
                sPIServersList.Add(PIServer.Key);
            }
            return sPIServersList.ToArray();
        }

        public int ValidateTagNames(string pitag1, string pitag2, string pitag3, string pitag4, string pitag5,int NumTags)
        {

            try
            {
                string PIPointUrl1 = baseUrl + "points?path=\\\\" + PIServerName + "\\" + pitag1;
                MyTag1 = MakeRequest(PIPointUrl1).Result;
                Object Id = MyTag1.Id.Value;
                MyTagName1 = pitag1;

                if (NumTags > 1)
                {
                    string PIPointUrl2 = baseUrl + "points?path=\\\\" + PIServerName + "\\" + pitag2;
                    MyTag2 = MakeRequest(PIPointUrl2).Result;
                    Object Id2 = MyTag2.Id.Value;
                    MyTagName2 = pitag2;
                }
                if (NumTags > 2)
                {
                    string PIPointUrl3 = baseUrl + "points?path=\\\\" + PIServerName + "\\" + pitag3;
                    MyTag3 = MakeRequest(PIPointUrl3).Result;
                    Object Id3 = MyTag3.Id.Value;
                    MyTagName3 = pitag3;
                }
                if (NumTags > 3)
                {
                    string PIPointUrl4 = baseUrl + "points?path=\\\\" + PIServerName + "\\" + pitag4;
                    MyTag4 = MakeRequest(PIPointUrl4).Result;
                    Object Id4 = MyTag4.Id.Value;
                    MyTagName4 = pitag4;
                }
                if (NumTags > 4)
                {
                    string PIPointUrl5 = baseUrl + "points?path=\\\\" + PIServerName + "\\" + pitag5;
                    MyTag5 = MakeRequest(PIPointUrl5).Result;
                    Object Id5 = MyTag5.Id.Value;
                    MyTagName5 = pitag5;
                }

            }
            catch
            {
                return 1;
            }

            return 0;

        }

        public PIValues GetRecordedValues(int i, string starttime, string endtime)
        {
            string PIPointRecData1Url;
            dynamic PIPointRecData;
            if (i==1)
            {
                PIPointRecData1Url = MyTag1.Links["Recorded Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime;
                PIPointRecData = MakeRequest(PIPointRecData1Url).Result;
            }
            else if (i==2)
            {
                PIPointRecData1Url = MyTag2.Links["Recorded Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime;
                PIPointRecData = MakeRequest(PIPointRecData1Url).Result;
            }
            else if (i==3)
            {
                PIPointRecData1Url = MyTag3.Links["Recorded Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime;
                PIPointRecData = MakeRequest(PIPointRecData1Url).Result;
            }
            else if (i==4)
            {
                PIPointRecData1Url = MyTag4.Links["Recorded Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime;
                PIPointRecData = MakeRequest(PIPointRecData1Url).Result;
            }
            else
            {
                PIPointRecData1Url = MyTag5.Links["Recorded Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime;
                PIPointRecData = MakeRequest(PIPointRecData1Url).Result;
            }
            return (ConvertToPIValues(PIPointRecData));

        }

        public PIValues GetInterpolatedValues(int i, string starttime, string endtime, string interval)
        {
            string PIPointIntData1Url;
            dynamic PIPointIntData;
            if (i == 1)
            {
                PIPointIntData1Url = MyTag1.Links["Interpolated Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime + "&interval=" + interval;
                PIPointIntData = MakeRequest(PIPointIntData1Url).Result;
            }
            else if (i == 2)
            {
                PIPointIntData1Url = MyTag2.Links["Interpolated Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime + "&interval=" + interval;
                PIPointIntData = MakeRequest(PIPointIntData1Url).Result;
            }
            else if (i == 3)
            {
                PIPointIntData1Url = MyTag3.Links["Interpolated Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime + "&interval=" + interval;
                PIPointIntData = MakeRequest(PIPointIntData1Url).Result;
            }
            else if (i == 4)
            {
                PIPointIntData1Url = MyTag4.Links["Interpolated Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime + "&interval=" + interval;
                PIPointIntData = MakeRequest(PIPointIntData1Url).Result;
            }
            else
            {
                PIPointIntData1Url = MyTag5.Links["Interpolated Data"].Value + "?starttime=" + starttime + "&endtime=" + endtime + "&interval=" + interval;
                PIPointIntData = MakeRequest(PIPointIntData1Url).Result;
            }
            return (ConvertToPIValues(PIPointIntData));
        }

        private PIValues ConvertToPIValues(dynamic RESTPIValues)
        {
            PIValues myPIValues = new PIValues();
            for (int i = 0; i < RESTPIValues.Items.Count; i++)
            {
                myPIValues.Add(new PIValue(RESTPIValues.Items[i].Value.Value, (DateTime)RESTPIValues.Items[i].Timestamp.Value));
            }

            return myPIValues;

        }

        private static async Task<dynamic> MakeRequest(string url)
        {
            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();

            using (StreamReader sw = new StreamReader(response.GetResponseStream()))
            {
                using (JsonTextReader reader = new JsonTextReader(sw))
                {
                    return JObject.ReadFrom(reader);
                }
            }
        }

        public void Disconnect()
        {

        }

    }
}


text:
title: Receiving Focus
page_title: Receiving Focus - RadMaskedTextBox
description: Check our Web Forms article about Receiving Focus.
slug: radmaskedtextbox/features/receiving-focus
tags: receiving,focus
published: True
position: 5
---

# Receiving Focus

How a **RadInput** control behaves when it receives focus can be controlled by setting the **SelectionOnFocus** property. It can be set to any of the following values:

* **Telerik.Web.UI.SelectionOnFocus.CaretToBeginning**: When the **SelectionOnFocus** property is **CaretToBeginning**, the input caret appears at the beginning of the input control's value when it first gets focus. Text the user types is inserted at the beginning of the control's current value.

* **Telerik.Web.UI.SelectionOnFocus.CaretToEnd**: When the **SelectionOnFocus** property is **CaretToEnd**, the input caret appears at the end of the input control's value when it first gets focus. Text the user types is appended to the control's current value.

* **Telerik.Web.UI.SelectionOnFocus.SelectAll**: When the **SelectionOnFocus** property is **SelectAll**, the entire value of the input control is selected when it first gets focus. Text the user types replaces the control's current value.

* **Telerik.Web.UI.SelectionOnFocus.None**: When the **SelectionOnFocus** property is **None** (the default value), the browser determines the caret placement and selection when the control first gets focus.

All four **RadInput** controls support the **SelectionOnFocus** property. In addition, two of the **RadMaskedTextBox**, let you format its values differently, depending on whether they have focus.

>caption

| RadInput Control | Properties for formatting value with focus | Properties for formatting value without focus |
| ------ | ------ | ------ |
|RadMaskedTextBox|Mask, PromptChar|DisplayMask, DisplayPromptChar|

>note You do not need to set both sets of properties. If you only set the properties for formatting a value with focus, the RadInput control uses them even if the control does not have focus.
>

# See Also

 * [Setting Focus]({%slug radmaskedtextbox/getting-started/setting-focus%})


text:
from office365.runtime.client_result import ClientResult
from office365.runtime.client_value_collection import ClientValueCollection
from office365.runtime.compat import is_string_type
from office365.runtime.http.http_method import HttpMethod
from office365.runtime.queries.service_operation import ServiceOperationQuery
from office365.runtime.paths.resource_path import ResourcePath
from office365.sharepoint.base_entity import BaseEntity
from office365.sharepoint.search.query.auto_completion_results import QueryAutoCompletionResults
from office365.sharepoint.search.query.popular_tenant_query import PopularTenantQuery
from office365.sharepoint.search.query.suggestion_results import QuerySuggestionResults
from office365.sharepoint.search.query.tenantCustomQuerySuggestions import TenantCustomQuerySuggestions
from office365.sharepoint.search.request import SearchRequest
from office365.sharepoint.search.result import SearchResult

class SearchService(BaseEntity):
    """SearchService exposes OData Service Operations."""

    def __init__(self, context):
        super(SearchService, self).__init__(context, ResourcePath("Microsoft.Office.Server.Search.REST.SearchService"))

    def export(self, user_name, start_time):
        """
        The operation is used by the administrator to retrieve the query log entries,
        issued after a specified date, for a specified user.

        :param datetime.datetime start_time: The timestamp of the oldest query log entry returned.
        :param str user_name: The name of the user that issued the queries."""
        result = ClientResult(self.context)
        payload = {
            "userName": user_name,
            "startTime": start_time.isoformat()
        }
        qry = ServiceOperationQuery(self, "export", None, payload, None, result)
        self.context.add_query(qry)
        return result

    def export_manual_suggestions(self):
        return_type = ClientResult(self.context, TenantCustomQuerySuggestions())
        qry = ServiceOperationQuery(self, "exportmanualsuggestions", None, None, None, return_type)
        self.context.add_query(qry)
        return return_type

    def export_popular_tenant_queries(self, count):
        """This method is used to get a list of popular search queries executed on the tenant.
        """
        return_type = ClientResult(self.context, ClientValueCollection(PopularTenantQuery))
        payload = {
            "count": count,
        }
        qry = ServiceOperationQuery(self, "exportpopulartenantqueries", None, payload, None, return_type)
        self.context.add_query(qry)
        return return_type

    def query(self, request_or_query):
        """The operation is used to retrieve search results by using the HTTP protocol with the GET method.

        :type request_or_query: office365.sharepoint.search.request.SearchRequest or str
        """
        if is_string_type(request_or_query):
            params = SearchRequest(query_text=request_or_query)
        else:
            params = request_or_query
        result = ClientResult(self.context, SearchResult())
        qry = ServiceOperationQuery(self, "query", params.to_json(), None, "query", result)
        self.context.add_query(qry)

        def _construct_request(request):
            """
            :type request: office365.runtime.http.request_options.RequestOptions
            """
            request.method = HttpMethod.Get

        self.context.before_execute(_construct_request)
        return result

    def post_query(self, query_text, select_properties=None, trim_duplicates=None, row_limit=None, **kwargs):
        """The operation is used to retrieve search results through the use of the HTTP protocol
        with method type POST.

        :param str query_text: The query text of the search query.
        :param list[str] select_properties: Specifies a property bag of key value pairs.
        :param bool trim_duplicates:  Specifies whether duplicates are removed by the protocol server before sorting,
             selecting, and sending the search results.
        :param int row_limit: The number of search results the protocol client wants to receive, starting at the index
            specified in the StartRow element. The RowLimit value MUST be greater than or equal to zero.
        """
        return_type = ClientResult(self.context, SearchResult())
        request = SearchRequest(query_text=query_text, select_properties=select_properties,
                                trim_duplicates=trim_duplicates, row_limit=row_limit, **kwargs)
        qry = ServiceOperationQuery(self, "postquery", None, request, "request", return_type)
        self.context.add_query(qry)
        return return_type

    def record_page_click(self):
        """The operation is used to record page clicks"""
        pass

    def search_center_url(self):
        """The operation is used to get the URI address of the search center by using the HTTP protocol
        with the GET method. The operation returns the URI of the of the search center."""
        return_type = ClientResult(self.context)
        qry = ServiceOperationQuery(self, "searchCenterUrl", None, None, None, return_type)
        self.context.add_query(qry)
        return return_type

    def results_page_address(self):
        """The operation is used to get the URI address of the result page by using the HTTP protocol
        with the GET method. The operation returns the URI of the result page."""
        pass

    def suggest(self, query_text):
        """
        :param str query_text: The query text of the search query. If this element is not present or a value
             is not specified, a default value of an empty string MUST be used, and the server MUST return a
             FaultException<ExceptionDetail> message.
        """
        return_type = ClientResult(self.context, QuerySuggestionResults())
        payload = {
            "querytext": query_text
        }
        qry = ServiceOperationQuery(self, "suggest", None, payload, None, return_type)
        self.context.add_query(qry)
        return return_type

    def auto_completions(self, query_text, sources=None, number_of_completions=None, cursor_position=None):
        """
        The operation is used to retrieve auto completion results by using the HTTP protocol with the GET method.

        :param str query_text: The query text of the search query. If this element is not present or a value is not
             specified, a default value of an empty string MUST be used, and the server MUST return
             a FaultException<ExceptionDetail> message.
        :param str sources: Specifies the sources that the protocol server SHOULD use when computing the result.
            If NULL, the protocol server SHOULD use all of the sources for autocompletions. The value SHOULD be a
            comma separated set of sources for autocompletions. The set of available sources the server SHOULD support
            is "Tag", which MAY be compiled from the set of #tags applied to documents. If the sources value is not
            a comma separated set of sources, or any of the source does not match "Tag", the server SHOULD return
            completions from all available sources.
        :param int number_of_completions: Specifies the maximum number query completion results in
            GetQueryCompletionsResponse response message.
        :param int cursor_position: Specifies the cursor position in the query text when this operation is sent
            to the protocol server.
        """
        return_type = ClientResult(self.context, QueryAutoCompletionResults())
        payload = {
            "querytext": query_text,
            "sources": sources,
            "numberOfCompletions": number_of_completions,
            "cursorPosition": cursor_position
        }
        qry = ServiceOperationQuery(self, "autocompletions", None, payload, None, return_type)
        self.context.add_query(qry)
        return return_type


text:
package org.glowroot.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import org.immutables.value.Value;

import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.SyntheticMonitorConfig.SyntheticMonitorKind;

@Value.Immutable
public abstract class SyntheticMonitorConfig {

    public abstract String id();

    public abstract SyntheticMonitorKind kind();

    // optional for type ping, required for type java
    @Value.Default
    @JsonInclude(Include.NON_EMPTY)
    public String display() {
        return "";
    }

    // === ping synthetic monitors ===

    @Value.Default
    @JsonInclude(Include.NON_EMPTY)
    public String pingUrl() {
        return "";
    }

    // === java synthetic monitors ===

    @Value.Default
    @JsonInclude(Include.NON_EMPTY)
    public String javaSource() {
        return "";
    }

    public static ImmutableSyntheticMonitorConfig create(
            AgentConfig.SyntheticMonitorConfig config) {
        return ImmutableSyntheticMonitorConfig.builder()
                .id(config.getId())
                .kind(config.getKind())
                .display(config.getDisplay())
                .pingUrl(config.getPingUrl())
                .javaSource(config.getJavaSource())
                .build();
    }

    public AgentConfig.SyntheticMonitorConfig toProto() {
        return AgentConfig.SyntheticMonitorConfig.newBuilder()
                .setId(id())
                .setDisplay(display())
                .setKind(kind())
                .setPingUrl(pingUrl())
                .setJavaSource(javaSource())
                .build();
    }
}


text:
require 'rest_client'
require 'base64'
require 'json'
require 'openssl'
require 'digest/sha2'
require 'logger'

module Bitfinex
  module Net
    INT_KEYS = [:reverse, :limit_trades, :order_id, :position_id, :limit, :offer_id, :swap_id]
    def self.to_uri(path)
      return "https://api.bitfinex.com#{path}"
    end

    def self.get(path, options={})
      begin
        RestClient.get(self.to_uri(path), :params => options)
      rescue RestClient::BadRequest => e
        raise BadRequest.new(e.response)
      end
    end

    def self.post(path, options={})
      options = stringify_value(options)
      begin
        RestClient.post(self.to_uri(path), {}, self.headers_for(path, options))
      rescue RestClient::BadRequest => e
        raise BadRequest.new(e.response)
      end
    end

    class BadRequest < RuntimeError; end

    private
    def self.stringify_value(hash)
      Hash[hash.map { |k, v| INT_KEYS.include?(k.to_sym) ? [k, v] : [k, v.to_s] }]
    end

    def self.headers_for(url, options={})
      payload = {}
      payload['request'] = url
      payload['nonce'] = (Time.now.to_f * 1_000_000_000).to_i.to_s
      payload.merge!(options)

      payload_enc = Base64.encode64(payload.to_json).gsub(/\s/, '')
      digest = OpenSSL::Digest.new('sha384')
      sig = OpenSSL::HMAC.hexdigest(digest, Bitfinex.secret, payload_enc)
      {
        'Content-Type' => 'application/json',
        'Accept' => 'application/json',
        'X-BFX-APIKEY' => Bitfinex.key,
        'X-BFX-PAYLOAD' => payload_enc,
        'X-BFX-SIGNATURE' => sig
      }
    end
  end
end


text:
Ti=Assignment

sec=A {_party} shall not assign this {_Agreement} or any of its rights or obligations hereunder without the other {_party}'s prior written consent. Subject to the preceding sentence, this {_Agreement} will inure to the benefit of the {_parties}' successors and assigns.

=[G/Z/ol/Base]


text:
var Patient = require('../models/patient');
var User = require('../models/user');
var _ = require('lodash');

module.exports = function (app, passport, isLoggedIn) {
  app.get('/patients',isLoggedIn, function (req, res) {

    var query = Patient.find({});
    query.where('_id').in(req.user.patient);

    query.exec(function (err,patients) {
      res.render('patient/list.ejs', {
        patients: patients
      });
    });
  })

  app.post('/patients/create', isLoggedIn, function (req, res) {

    User.findOne({_id: req.user._id}, function(err, caregiver) {

      var patient = new Patient({
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        birth_date: req.body.birth_date,
        caregiver: req.user._id
      });

      caregiver.patient.push(patient._id);

      caregiver.save();

      patient.save();
      res.redirect('/');
    })

  })

  app.get('/patients/create', isLoggedIn, function (req, res) {
    res.render('patient/create.ejs');
  })

  app.post('/patients/last_known_position', function(req, res) {
    var location_x = req.body.x;
    var location_y = req.body.y;

    Patient.findOne({_id: "563f57fc04e428b37dfd033a"}, function (err, patient) {
      patient.last_known_position.x = location_x;
      patient.last_known_position.y = location_y;
      patient.save();

      res.status(200).send('OK');
    })

  });

  app.get('/patients/:id', isLoggedIn, isAuthorized, function(req, res) {
    Patient.findOne({_id:req.params.id}, function (err, patient) {
      if (!err) {
        res.render('patient/profile.ejs',{
          patient: patient
        });
      }
    })

  })

}

function isAuthorized(req, res, next) {
  User.findOne({ _id : req.user._id }, function(err, user) {
    var exists = _.find(user.patient, function(patient) {
      if (patient == req.params.id) {
        return true;
      }

      return false;
    })

    if (exists) {
      return next();
    }

    req.flash("error", "Not Authorized to Access Records");
    res.redirect("/");
  })
}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import logging
import Queue
import threading

from pants.pantsd.service.pants_service import PantsService

class SchedulerService(PantsService):
  """The pantsd scheduler service.

  This service holds an online Scheduler instance that is primed via watchman filesystem events.
  This provides for a quick fork of pants runs (via the pailgun) with a fully primed ProductGraph
  in memory.
  """

  def __init__(self, fs_event_service, legacy_graph_helper):
    """
    :param FSEventService fs_event_service: An unstarted FSEventService instance for setting up
                                            filesystem event handlers.
    :param LegacyGraphHelper legacy_graph_helper: The LegacyGraphHelper instance for graph
                                                  construction.
    """
    super(SchedulerService, self).__init__()
    self._fs_event_service = fs_event_service
    self._graph_helper = legacy_graph_helper
    self._scheduler = legacy_graph_helper.scheduler

    self._logger = logging.getLogger(__name__)
    self._event_queue = Queue.Queue(maxsize=64)
    self._ready = threading.Event()

  @property
  def change_calculator(self):
    """Surfaces the change calculator."""
    return self._graph_helper.change_calculator

  def setup(self, lock):
    """Service setup."""
    super(SchedulerService, self).setup(lock)
    # Register filesystem event handlers on an FSEventService instance.
    self._fs_event_service.register_all_files_handler(self._enqueue_fs_event)

  def _enqueue_fs_event(self, event):
    """Watchman filesystem event handler for BUILD/requirements.txt updates. Called via a thread."""
    self._logger.info('enqueuing {} changes for subscription {}'
                      .format(len(event['files']), event['subscription']))
    self._event_queue.put(event)

  def _handle_batch_event(self, files):
    self._logger.debug('handling change event for: %s', files)
    self._scheduler.invalidate_files(files)

  def _process_event_queue(self):
    """File event notification queue processor."""
    try:
      event = self._event_queue.get(timeout=1)
    except Queue.Empty:
      return

    with self.lock:
      try:
        subscription, is_initial_event, files = (event['subscription'],
                                                 event['is_fresh_instance'],
                                                 [f.decode('utf-8') for f in event['files']])
      except (KeyError, UnicodeDecodeError) as e:
        self._logger.warn('%r raised by invalid watchman event: %s', e, event)
        return

      self._logger.debug('processing {} files for subscription {} (first_event={})'
                         .format(len(files), subscription, is_initial_event))

      # The first watchman event is a listing of all files - ignore it.
      if not is_initial_event:
        self._handle_batch_event(files)

    if not self._ready.is_set(): self._ready.set()
    self._event_queue.task_done()

  def warm_product_graph(self, spec_roots):
    """Runs an execution request against the captive scheduler given a set of input specs to warm.

    :returns: A `LegacyGraphHelper` instance for graph construction.
    """
    # Block warming until the initial watchman filesystem event is seen.
    self._ready.wait()

    with self.lock:
      self._graph_helper.warm_product_graph(spec_roots)
      return self._graph_helper

  def run(self):
    """Main service entrypoint."""
    while not self.is_killed:
      self._process_event_queue()


text:
All files in `core/data/static` are data that should not be bundled in the extension. They will evolve with time. They depend on `gwent-data-release` in particular.

They are exposed here for testing purpose and to build the card data API on the website,

If the extension needs something there, it should instead fetch an updated version from a Web API.


text:
<plugin id="filter" groups="topic,topicmap">
  <title>Filter</title>
  <descr>Configure a context filter for this topic map.</descr>
  <activated>yes</activated>
  <uri>${plugins_rootdir}/filter/userContextFilter.jsp</uri>
</plugin>


text:
package ql

import (
	"bytes"
	"database/sql"
	"database/sql/driver"
	"errors"
	"fmt"
	"io"
	"math/big"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

var (
	_ driver.Conn    = (*driverConn)(nil)
	_ driver.Driver  = (*sqlDriver)(nil)
	_ driver.Execer  = (*driverConn)(nil)
	_ driver.Queryer = (*driverConn)(nil)
	_ driver.Result  = (*driverResult)(nil)
	_ driver.Rows    = (*driverRows)(nil)
	_ driver.Stmt    = (*driverStmt)(nil)
	_ driver.Tx      = (*driverConn)(nil)

	txBegin    = MustCompile("BEGIN TRANSACTION;")
	txCommit   = MustCompile("COMMIT;")
	txRollback = MustCompile("ROLLBACK;")

	errNoResult = errors.New("query statement does not produce a result set (no top level SELECT)")
)

type errList []error

func (e *errList) append(err error) {
	if err != nil {
		*e = append(*e, err)
	}
}

func (e errList) error() error {
	if len(e) == 0 {
		return nil
	}

	return e
}

func (e errList) Error() string {
	a := make([]string, len(e))
	for i, v := range e {
		a[i] = v.Error()
	}
	return strings.Join(a, "\n")
}

func params(args []driver.Value) []interface{} {
	r := make([]interface{}, len(args))
	for i, v := range args {
		r[i] = interface{}(v)
	}
	return r
}

var (
	fileDriver     = &sqlDriver{dbs: map[string]*driverDB{}}
	fileDriverOnce sync.Once
	memDriver      = &sqlDriver{isMem: true, dbs: map[string]*driverDB{}}
	memDriverOnce  sync.Once
)

// RegisterDriver registers a QL database/sql/driver[0] named "ql". The name
// parameter of
//
//	sql.Open("ql", name)
//
// is interpreted as a path name to a named DB file which will be created if
// not present. The underlying QL database data are persisted on db.Close().
// RegisterDriver can be safely called multiple times, it'll register the
// driver only once.
//
// The name argument can be optionally prefixed by "file://". In that case the
// prefix is stripped before interpreting it as a file name.
//
// The name argument can be optionally prefixed by "memory://". In that case
// the prefix is stripped before interpreting it as a name of a memory-only,
// volatile DB.
//
//  [0]: http://golang.org/pkg/database/sql/driver/
func RegisterDriver() {
	fileDriverOnce.Do(func() { sql.Register("ql", fileDriver) })
}

// RegisterMemDriver registers a QL memory database/sql/driver[0] named
// "ql-mem".  The name parameter of
//
//	sql.Open("ql-mem", name)
//
// is interpreted as an unique memory DB name which will be created if not
// present. The underlying QL memory database data are not persisted on
// db.Close(). RegisterMemDriver can be safely called multiple times, it'll
// register the driver only once.
//
//  [0]: http://golang.org/pkg/database/sql/driver/
func RegisterMemDriver() {
	memDriverOnce.Do(func() { sql.Register("ql-mem", memDriver) })
}

type driverDB struct {
	db       *DB
	name     string
	refcount int
}

func newDriverDB(db *DB, name string) *driverDB {
	return &driverDB{db: db, name: name, refcount: 1}
}

// sqlDriver implements the interface required by database/sql/driver.
type sqlDriver struct {
	dbs   map[string]*driverDB
	isMem bool
	mu    sync.Mutex
}

func (d *sqlDriver) lock() func() {
	d.mu.Lock()
	return d.mu.Unlock
}

// Open returns a new connection to the database.  The name is a string in a
// driver-specific format.
//
// Open may return a cached connection (one previously closed), but doing so is
// unnecessary; the sql package maintains a pool of idle connections for
// efficient re-use.
//
// The returned connection is only used by one goroutine at a time.
func (d *sqlDriver) Open(name string) (driver.Conn, error) {
	if d != fileDriver && d != memDriver {
		return nil, fmt.Errorf("open: unexpected/unsupported instance of driver.Driver: %p", d)
	}

	switch {
	case d == fileDriver && strings.HasPrefix(name, "file://"):
		name = name[len("file://"):]
	case d == fileDriver && strings.HasPrefix(name, "memory://"):
		d = memDriver
		name = name[len("memory://"):]
	}
	name = filepath.Clean(name)
	if name == "" || name == "." || name == string(os.PathSeparator) {
		return nil, fmt.Errorf("invalid DB name %q", name)
	}

	defer d.lock()()
	db := d.dbs[name]
	if db == nil {
		var err error
		var db0 *DB
		switch d.isMem {
		case true:
			db0, err = OpenMem()
		default:
			db0, err = OpenFile(name, &Options{CanCreate: true})
		}
		if err != nil {
			return nil, err
		}

		db = newDriverDB(db0, name)
		d.dbs[name] = db
		return newDriverConn(d, db), nil
	}

	db.refcount++
	return newDriverConn(d, db), nil
}

// driverConn is a connection to a database. It is not used concurrently by
// multiple goroutines.
//
// Conn is assumed to be stateful.
type driverConn struct {
	ctx    *TCtx
	db     *driverDB
	driver *sqlDriver
	stop   map[*driverStmt]struct{}
	tnl    int
}

func newDriverConn(d *sqlDriver, ddb *driverDB) driver.Conn {
	r := &driverConn{
		db:     ddb,
		driver: d,
		stop:   map[*driverStmt]struct{}{},
	}
	return r
}

// Prepare returns a prepared statement, bound to this connection.
func (c *driverConn) Prepare(query string) (driver.Stmt, error) {
	list, err := Compile(query)
	if err != nil {
		return nil, err
	}

	s := &driverStmt{conn: c, stmt: list}
	c.stop[s] = struct{}{}
	return s, nil
}

// Close invalidates and potentially stops any current prepared statements and
// transactions, marking this connection as no longer in use.
//
// Because the sql package maintains a free pool of connections and only calls
// Close when there's a surplus of idle connections, it shouldn't be necessary
// for drivers to do their own connection caching.
func (c *driverConn) Close() error {
	var err errList
	for s := range c.stop {
		err.append(s.Close())
	}
	defer c.driver.lock()()
	dbs, name := c.driver.dbs, c.db.name
	v := dbs[name]
	v.refcount--
	if v.refcount == 0 {
		err.append(c.db.db.Close())
		delete(dbs, name)
	}
	return err.error()
}

// Begin starts and returns a new transaction.
func (c *driverConn) Begin() (driver.Tx, error) {
	if c.ctx == nil {
		c.ctx = NewRWCtx()
	}

	if _, _, err := c.db.db.Execute(c.ctx, txBegin); err != nil {
		return nil, err
	}

	c.tnl++
	return c, nil
}

func (c *driverConn) Commit() error {
	if c.tnl == 0 || c.ctx == nil {
		return errCommitNotInTransaction
	}

	if _, _, err := c.db.db.Execute(c.ctx, txCommit); err != nil {
		return err
	}

	c.tnl--
	if c.tnl == 0 {
		c.ctx = nil
	}
	return nil
}

func (c *driverConn) Rollback() error {
	if c.tnl == 0 || c.ctx == nil {
		return errRollbackNotInTransaction
	}

	if _, _, err := c.db.db.Execute(c.ctx, txRollback); err != nil {
		return err
	}

	c.tnl--
	if c.tnl == 0 {
		c.ctx = nil
	}
	return nil
}

// Execer is an optional interface that may be implemented by a Conn.
//
// If a Conn does not implement Execer, the sql package's DB.Exec will first
// prepare a query, execute the statement, and then close the statement.
//
// Exec may return driver.ErrSkip.
func (c *driverConn) Exec(query string, args []driver.Value) (driver.Result, error) {
	list, err := Compile(query)
	if err != nil {
		return nil, err
	}

	return driverExec(c.db, c.ctx, list, args)
}

func driverExec(db *driverDB, ctx *TCtx, list List, args []driver.Value) (driver.Result, error) {
	if _, _, err := db.db.Execute(ctx, list, params(args)...); err != nil {
		return nil, err
	}

	if len(list.l) == 1 {
		switch list.l[0].(type) {
		case *createTableStmt, *dropTableStmt, *alterTableAddStmt,
			*alterTableDropColumnStmt, *truncateTableStmt:
			return driver.ResultNoRows, nil
		}
	}

	r := &driverResult{}
	if ctx != nil {
		r.lastInsertID, r.rowsAffected = ctx.LastInsertID, ctx.RowsAffected
	}
	return r, nil
}

// Queryer is an optional interface that may be implemented by a Conn.
//
// If a Conn does not implement Queryer, the sql package's DB.Query will first
// prepare a query, execute the statement, and then close the statement.
//
// Query may return driver.ErrSkip.
func (c *driverConn) Query(query string, args []driver.Value) (driver.Rows, error) {
	list, err := Compile(query)
	if err != nil {
		return nil, err
	}

	return driverQuery(c.db, c.ctx, list, args)
}

func driverQuery(db *driverDB, ctx *TCtx, list List, args []driver.Value) (driver.Rows, error) {
	rss, _, err := db.db.Execute(ctx, list, params(args)...)
	if err != nil {
		return nil, err
	}

	switch n := len(rss); n {
	case 0:
		return nil, errNoResult
	case 1:
		return newdriverRows(rss[len(rss)-1]), nil
	default:
		return nil, fmt.Errorf("query produced %d result sets, expected only one", n)
	}
}

// driverResult is the result of a query execution.
type driverResult struct {
	lastInsertID int64
	rowsAffected int64
}

// LastInsertId returns the database's auto-generated ID after, for example, an
// INSERT into a table with primary key.
func (r *driverResult) LastInsertId() (int64, error) { // -golint
	return r.lastInsertID, nil
}

// RowsAffected returns the number of rows affected by the query.
func (r *driverResult) RowsAffected() (int64, error) {
	return r.rowsAffected, nil
}

// driverRows is an iterator over an executed query's results.
type driverRows struct {
	rs   Recordset
	done chan int
	rows chan interface{}
}

func newdriverRows(rs Recordset) *driverRows {
	r := &driverRows{
		rs:   rs,
		done: make(chan int),
		rows: make(chan interface{}, 500),
	}
	go func() {
		err := io.EOF
		if e := r.rs.Do(false, func(data []interface{}) (bool, error) {
			select {
			case r.rows <- data:
				return true, nil
			case <-r.done:
				return false, nil
			}
		}); e != nil {
			err = e
		}

		select {
		case r.rows <- err:
		case <-r.done:
		}
	}()
	return r
}

// Columns returns the names of the columns. The number of columns of the
// result is inferred from the length of the slice.  If a particular column
// name isn't known, an empty string should be returned for that entry.
func (r *driverRows) Columns() []string {
	f, _ := r.rs.Fields()
	return f
}

// Close closes the rows iterator.
func (r *driverRows) Close() error {
	close(r.done)
	return nil
}

// Next is called to populate the next row of data into the provided slice. The
// provided slice will be the same size as the Columns() are wide.
//
// The dest slice may be populated only with a driver Value type, but excluding
// string.  All string values must be converted to []byte.
//
// Next should return io.EOF when there are no more rows.
func (r *driverRows) Next(dest []driver.Value) error {
	select {
	case rx := <-r.rows:
		switch x := rx.(type) {
		case error:
			return x
		case []interface{}:
			if g, e := len(x), len(dest); g != e {
				return fmt.Errorf("field count mismatch: got %d, need %d", g, e)
			}

			for i, xi := range x {
				switch v := xi.(type) {
				case nil, int64, float64, bool, []byte, time.Time:
					dest[i] = v
				case complex64, complex128, *big.Int, *big.Rat:
					var buf bytes.Buffer
					fmt.Fprintf(&buf, "%v", v)
					dest[i] = buf.Bytes()
				case int8:
					dest[i] = int64(v)
				case int16:
					dest[i] = int64(v)
				case int32:
					dest[i] = int64(v)
				case int:
					dest[i] = int64(v)
				case uint8:
					dest[i] = int64(v)
				case uint16:
					dest[i] = int64(v)
				case uint32:
					dest[i] = int64(v)
				case uint64:
					dest[i] = int64(v)
				case uint:
					dest[i] = int64(v)
				case time.Duration:
					dest[i] = int64(v)
				case string:
					dest[i] = []byte(v)
				default:
					return fmt.Errorf("internal error 004")
				}
			}
			return nil
		default:
			return fmt.Errorf("internal error 005")
		}
	case <-r.done:
		return io.EOF
	}
}

// driverStmt is a prepared statement. It is bound to a driverConn and not used
// by multiple goroutines concurrently.
type driverStmt struct {
	conn *driverConn
	stmt List
}

// Close closes the statement.
//
// As of Go 1.1, a Stmt will not be closed if it's in use by any queries.
func (s *driverStmt) Close() error {
	delete(s.conn.stop, s)
	return nil
}

// NumInput returns the number of placeholder parameters.
//
// If NumInput returns >= 0, the sql package will sanity check argument counts
// from callers and return errors to the caller before the statement's Exec or
// Query methods are called.
//
// NumInput may also return -1, if the driver doesn't know its number of
// placeholders. In that case, the sql package will not sanity check Exec or
// Query argument counts.
func (s *driverStmt) NumInput() int {
	if x := s.stmt; len(x.l) == 1 {
		return x.params
	}

	return -1
}

// Exec executes a query that doesn't return rows, such as an INSERT or UPDATE.
func (s *driverStmt) Exec(args []driver.Value) (driver.Result, error) {
	c := s.conn
	return driverExec(c.db, c.ctx, s.stmt, args)
}

// Exec executes a query that may return rows, such as a SELECT.
func (s *driverStmt) Query(args []driver.Value) (driver.Rows, error) {
	c := s.conn
	return driverQuery(c.db, c.ctx, s.stmt, args)
}


text:
@interface PSPDFDocumentProvider : NSObject

/// Initializes provider with a document reference.
- (id)initWithDocumentRef:(CGPDFDocumentRef)documentRef URL:(NSURL *)URL;

/// Get access to document reference.
- (CGPDFDocumentRef)requestDocumentRef;

/// Return the document reference back to the provider
- (void)releaseDocumentRef:(CGPDFDocumentRef)documentRef;

/// Requests a page for the current loaded document. Needs to be returned in releasePageRef.
- (CGPDFPageRef)requestPageRefForPage:(NSUInteger)page;

/// Releases a page reference.
- (void)releasePageRef:(CGPDFPageRef)pageRef;

/// URL of the managed document
@property(nonatomic, strong, readonly) NSURL *URL;

@end


text:
package router

import (
	"errors"
	"fmt"

	"github.com/golang/glog"
	"github.com/spf13/cobra"

	"github.com/openshift/origin/pkg/cmd/util"
	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
	"github.com/openshift/origin/pkg/router"
	controllerfactory "github.com/openshift/origin/pkg/router/controller/factory"
	"github.com/openshift/origin/pkg/util/proc"
	"github.com/openshift/origin/pkg/version"
	templateplugin "github.com/openshift/origin/plugins/router/template"
)

const (
	router_long = `Start an OpenShift router.

This command launches a router connected to your OpenShift master. The router listens for routes and endpoints
created by users and keeps a local router configuration up to date with those changes.`
)

type templateRouterConfig struct {
	Config             *clientcmd.Config
	TemplateFile       string
	ReloadScript       string
	DefaultCertificate string
}

// NewCommndTemplateRouter provides CLI handler for the template router backend
func NewCommandTemplateRouter(name string) *cobra.Command {
	cfg := &templateRouterConfig{
		Config: clientcmd.NewConfig(),
	}

	cmd := &cobra.Command{
		Use:   fmt.Sprintf("%s%s", name, clientcmd.ConfigSyntax),
		Short: "Start an OpenShift router",
		Long:  router_long,
		Run: func(c *cobra.Command, args []string) {
			defaultCert := util.Env("DEFAULT_CERTIFICATE", "")
			if len(defaultCert) > 0 {
				cfg.DefaultCertificate = defaultCert
			}

			plugin, err := makeTemplatePlugin(cfg)
			if err != nil {
				glog.Fatal(err)
			}

			if err = start(cfg.Config, plugin); err != nil {
				glog.Fatal(err)
			}
		},
	}

	cmd.AddCommand(version.NewVersionCommand(name))

	flag := cmd.Flags()
	cfg.Config.Bind(flag)
	flag.StringVar(&cfg.TemplateFile, "template", util.Env("TEMPLATE_FILE", ""), "The path to the template file to use")
	flag.StringVar(&cfg.ReloadScript, "reload", util.Env("RELOAD_SCRIPT", ""), "The path to the reload script to use")

	return cmd
}

func makeTemplatePlugin(cfg *templateRouterConfig) (*templateplugin.TemplatePlugin, error) {
	if cfg.TemplateFile == "" {
		return nil, errors.New("Template file must be specified")
	}

	if cfg.ReloadScript == "" {
		return nil, errors.New("Reload script must be specified")
	}

	return templateplugin.NewTemplatePlugin(cfg.TemplateFile, cfg.ReloadScript, cfg.DefaultCertificate)
}

// start launches the load balancer.
func start(cfg *clientcmd.Config, plugin router.Plugin) error {
	osClient, kubeClient, err := cfg.Clients()
	if err != nil {
		return err
	}

	proc.StartReaper()

	factory := controllerfactory.RouterControllerFactory{KClient: kubeClient, OSClient: osClient}
	controller := factory.Create(plugin)
	controller.Run()

	select {}

	return nil
}


text:
from sys import argv,exit
from os.path import split
from BitTornado.bencode import bencode, bdecode

def give_announce_list(l):
    list = []
    for tier in l:
        for tracker in tier:
            list+=[tracker,',']
        del list[-1]
        list+=['|']
    del list[-1]
    liststring = ''
    for i in list:
        liststring+=i
    return liststring

if len(argv) < 3:
    a,b = split(argv[0])
    print 'Usage: ' + b + ' <source.torrent> <file1.torrent> [file2.torrent...]'
    print 'copies announce information from source to all specified torrents'
    exit(2) # common exit code for syntax error

h = open(argv[1], 'rb')
source_metainfo = bdecode(h.read())
h.close()

print 'new announce: ' + source_metainfo['announce']
if source_metainfo.has_key('announce-list'):
    print 'new announce-list: ' + give_announce_list(source_metainfo['announce-list'])

for f in argv[2:]:
    h = open(f, 'rb')
    metainfo = bdecode(h.read())
    h.close()
    print 'old announce for %s: %s' % (f, metainfo['announce'])
    metainfo['announce'] = source_metainfo['announce']
    if metainfo.has_key('announce-list'):
        print 'old announce-list for %s: %s' % (f, give_announce_list(metainfo['announce-list']))
    if source_metainfo.has_key('announce-list'):
        metainfo['announce-list'] = source_metainfo['announce-list']
    elif metainfo.has_key('announce-list'):
        try:
            del metainfo['announce-list']
        except:
            pass

    h = open(f, 'wb')
    h.write(bencode(metainfo))
    h.close()