text:
(function(L) {
    "use strict";

    L.Control.AltitudeProfile = L.Control.extend({
        _profileData: null,
        _profileInfo: null,

        _chartContainer: null,
        _canvas: null,

        _map: null,
        _chart: null,
        _currentPointMarker: null,
        _buttonElement: null,

        _currentHoverTimer: null,

        options: {
            position: 'topleft',
            iconBaseUrl: null,
            //Color used to plot the chart line
            chartLineColor: '#003ac1',
            //Background color of the char tooltip
            tooltipBackgroundColor: 'rgba(81,81,81,0.80)',
            //How much time has to pass since
            //  the last chart hover event before
            //  the map is adjusted to move the highlighted
            //  marker into vie
            hoverPanTimeout: 75,
            //Labels used when constructing the chart tooltip
            labels: {
                altitude: 'Altitude:',
                distance: 'Distance:'
            }
        },

        _removeCurrentHighlightedProfilePoint: function() {
            if (this._currentPointMarker != null) {
                this._map.removeControl(this._currentPointMarker);
                this._currentPointMarker = null;
            }
        },

        _cancelHoverTimer: function() {
            if (this._currentHoverTimer !== null) {
                window.clearTimeout(this._currentHoverTimer);
                this._currentHoverTimer = null;
            }
        },

        _highlightProfilePoint: function(point) {
            var me = this;
            var icon = L.icon({
                iconUrl: this.options.iconBaseUrl + '/blip.png',
                iconSize: [24, 28],
                iconAnchor: [12, 28]
            });

            var markerCoord = L.latLng(point.coord.lat,
                point.coord.lng);

            if (this._currentPointMarker != null) {
                this._map.removeControl(this._currentPointMarker);
            }

            //See if the marker is within the current bounds of the map
            //  If not, start a timer to move the marker into view.
            //  We're using a timer because, if the user
            //  shuflles rapidly between chart positions
            //  we're going to have a lot of useless pans
            if (!this._map.getBounds().contains(markerCoord)) {
                //First, cancel out the existing timer
                this._cancelHoverTimer();

                //Start a new one
                this._currentHoverTimer = window.setTimeout(function() {
                    me._currentHoverTimer = null;
                    me._map.panTo(markerCoord);
                }, this.options.hoverPanTimeout);
            }

            //Add the point anyway
            this._currentPointMarker = L.marker(markerCoord, {
                icon: icon
            }).addTo(this._map);
        },

        _getProfileDataSource: function() {
            var labels = [];
            var values = [];

            for (var i = 0; i < this._profileData.profile.length; i ++) {
                var profileDataItem = this._profileData.profile[i];
                labels.push(Math.round(profileDataItem.displayDistance) + ' ' + this._profileData.distanceUnit);
                values.push(profileDataItem.displayAlt);
            }

            return {
                labels: labels,
                values: values
            };
        },

        _tryGetActivePoint: function() {
            var point = null;
            if (!!this._chart.tooltip
                && this._chart.tooltip._active
                && this._chart.tooltip._active[0]) {
                var tooltip = this._chart.tooltip._active[0];
                if (tooltip.hasOwnProperty('_index') && tooltip._index !== null) {
                    point = this._profileData.profile[tooltip._index];
                }
            }
            return point;
        },

        _determineYAxisStepSize: function() {
            var deltaAlt = Math.abs(this._profileInfo.maxAltitude.value
                - this._profileInfo.minAltitude.value);

            //If beween the minimum altitude and maximum altitude
            //  the difference is greater than 1000 units
            //  use a step size of 100
            if (deltaAlt >= 1000) {
                return 100;
            }
            //If between 500 and 1000, use a step size of 70
            if (deltaAlt > 500) {
                return 70;
            }
            //If between 100 and 500, use a step size of 50
            if (deltaAlt > 100) {
                return 50;
            }

            //If below or at most 100, use a step size of 10
            return 10;
        },

        _createProfileChart: function(context) {
            var me = this;
            var dataSource = this._getProfileDataSource();
            me._chart = new Chart(context, {
                type: 'line',

                data: {
                    labels: dataSource.labels,
                    datasets: [{
                        borderColor: me.options.chartLineColor,
                        data: dataSource.values
                    }]
                },

                options: {
                    legend: {
                        display: false
                    },

                    scales: {
                        yAxes: [{
                           ticks: {
                              stepSize: me._determineYAxisStepSize()
                           }
                        }]
                    },

                    onHover: function(event, data) {
                        var point = me._tryGetActivePoint();
                        if (point) {
                            me._highlightProfilePoint(point);
                        }
                    },

                    tooltips: {
                        position: 'nearest',
                        intersect: false,
                        displayColors: false,
                        backgroundColor: me.options.tooltipBackgroundColor,
                        callbacks: {
                            beforeLabel: function() {
                                return '';
                            },
                            label: function(item, data) {
                                return me.options.labels.altitude + ' ' + item.yLabel;
                            },
                            beforeTitle: function(item, data) {
                                return me.options.labels.distance + ' ';
                            },
                            afterLabel: function(item, data) {
                                return me._profileData.heightUnit;
                            }
                        }
                    },

                    hover: {
                        animationDuration: 0
                    }
                }
            });
        },

        _showProfileChart: function() {
            this._canvas = L.DomUtil.create('canvas', 'abp01-techbox-altitude-profile',
                this._chartContainer);

            var context = this._canvas
                .getContext('2d');

            this._createProfileChart(context);

            L.DomEvent.on(this._chartContainer,
                'mouseleave',
                this._handleChartAreaLeave,
                this);
        },

        _hideProfileChart: function() {
            if (this._chart != null) {
                //Remove the currently highlighted point from the map
                this._removeCurrentHighlightedProfilePoint();

                //Unbind event listeners
                L.DomEvent.off(this._chartContainer,
                    'mouseleave',
                    this._handleChartAreaLeave,
                    this);

                //Destroy chart
                this._chart.destroy();
                this._chart = null;

                //Empty chart container
                L.DomUtil.empty(this._chartContainer);
            }
        },

        _handleChartAreaLeave: function() {
            //When the mouse pointer leaves the chart area,
            //  remove the map marker that highlights
            //  the current point on the profile
            //  and cancel the hover timer, so that
            //  the map won't needlessly move
            this._cancelHoverTimer();
            this._removeCurrentHighlightedProfilePoint();
        },

        _createButton: function() {
            var buttonInfo = L.DomUtil.createMapButton({
                handleButtonClicked: this._handleButtonClicked,
                eventContext: this,
                iconCssClass: 'dashicons-chart-area',
                additionalCssClass: 'abp01-map-altitude-profile-btn'
            });

            this._buttonElement = buttonInfo.buttonElement;
            return buttonInfo.container;
        },

        _handleButtonClicked: function(event) {
            //Toggle chart on or off
            if (this._chart == null) {
                this._showProfileChart();
            } else {
                this._hideProfileChart();
            }

            L.DomEvent.preventDefault(event);
            L.DomEvent.stopPropagation(event);
        },

        initialize: function(chartContainer, profileData, profileInfo, options) {
            if (chartContainer == null) {
                throw new Error('Container is required');
            }

            if (profileData == null) {
                throw new Error('Profile data is required');
            }

            if (profileInfo == null) {
                throw new Error('Profile info is required');
            }

            this._chartContainer = L.DomUtil.get(chartContainer);
            this._profileData = profileData;
            this._profileInfo = profileInfo;

            L.Util.setOptions(this, options || {});
        },

        onAdd: function(map) {
            this._map = map;
            return this._createButton();
        },

        onRemove: function(map) {
            //Unbind toggler event listeners
            L.DomEvent.off(this._buttonElement,
                'click',
                this._handleButtonClicked,
                this);

            //Destroy chart if shown
            if (this._chart != null) {
                this._hideProfileChart();
            }

            //Cleanup the rest of stuff
            this._buttonElement = null;
        }
    });

    L.control.altitudeProfile = function(container, data, labels, options) {
        return new L.Control.AltitudeProfile(container, data, labels, options);
    };
})(window.abp01Leaflet);


text:
package org.ow2.chameleon.fuchsia.examples.jsonrpc.exporter.experiment;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Provides;

/**
 * Created with IntelliJ IDEA.
 * User: jnascimento
 * Date: 27/01/14
 * Time: 10:17
 * To change this template use File | Settings | File Templates.
 */
@Component
@Instantiate(name = "DummyPojoInstance")
@Provides
public class DummyPojo implements DummyIface {

    public void helloworld(String value) {

        System.out.println("hello " + value);

    }

}

redpajama_set_name: RedPajamaGithub


text:
<html lang="en">
<head>
    <title>Title</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>

<body>


text:
define(["mithril", "lodash", "pipeline_configs/views/lookup_command_widget", "pipeline_configs/models/tasks"], function (m, _, LookupCommandWidget, Tasks) {
  describe("Lookup Command Widget", function () {
    var $root, root;

    function createRootElement() {
      root = document.createElement("div");
      document.body.appendChild(root);
      $root = $(root);
    }

    function mount(model, snippet) {
      m.mount(root,
        m.component(LookupCommandWidget, {model: model, snippet: snippet})
      );
      m.redraw(true);
    }

    describe("view", function() {
      var model, snippet, enableTextComplete;

      beforeAll(function(){
        model = new Tasks.Task.Exec({command: 'ls'});
        snippet = new LookupCommandWidget.Command.Snippet({
          name:          'scp',
          description:   'scp desc',
          author:        'go team',
          author_info:   'tw',
          more_info:     'more',
          command:       'scp',
          arguments:     ['src', 'dest'],
          relative_path: '/build/scp.xml'
        });

        enableTextComplete = jasmine.createSpy('enableTextComplete');

        spyOn(LookupCommandWidget.Command, 'textComplete').and.callFake(function () {
          return enableTextComplete;
        });

        createRootElement();
        mount(model, snippet);
      });

      afterAll(function () {
        root.parentNode.removeChild(root);
      });

      it("should render a text box with textcomplete enabled", function () {
        expect($root.find("input[name=lookup]").size()).toBe(1);
        expect(enableTextComplete).toHaveBeenCalled();
      });

      it("should render the command snippet title", function () {
        expect($root.find(".snippet>header>h5.snippet-title").text()).toBe(snippet.name());
      });

      it("should render snippet description with more info", function () {
        expect($root.find(".snippet>p").text()).toBe(snippet.description() + "more info");
        expect($root.find(".snippet>p>a").attr('href')).toBe(snippet.moreInfo());
      });

      it("should render the snippet author info", function() {
        expect($root.find(".snippet>header>div.author>a").text()).toBe(snippet.author());
        expect($root.find(".snippet>header>div.author>a").attr('href')).toBe(snippet.authorInfo());
      });
    });

    describe('controller', function () {
      describe('selectSnippet', function () {
        var snippet;
        beforeEach(function(){
          snippet = new LookupCommandWidget.Command.Snippet({
            name:      'build',
            command:   'maven',
            arguments: ['clean', 'build']
          });
          spyOn(m, 'redraw');
        });

        it('should update task command and arguments', function () {
          var task = new Tasks.Task.Exec({command: 'ls', arguments: ['-al']});
          var controller = new LookupCommandWidget.controller({
            model:    task,
            snippets: new LookupCommandWidget.Command.Snippets([snippet])
          });

          controller.selectSnippet(null, 'build');

          expect(task.command()).toEqual(snippet.command());
          expect(task.args().data()).toEqual(snippet.arguments());
          expect(m.redraw).toHaveBeenCalled();
        });
      });

      describe('searchSnippet', function () {
        var deferred;

        beforeEach(function () {
          deferred = $.Deferred();

          spyOn(LookupCommandWidget.Command, 'lookup').and.callFake(function () {
            return deferred.promise();
          });
        });

        it('should lookup for command snippets for a search term', function () {
          new LookupCommandWidget.controller({}).searchSnippets('scp');

          expect(LookupCommandWidget.Command.lookup).toHaveBeenCalledWith('scp');
        });

        it('should call the textcomplete callback with snippet names on success of lookup', function () {
          var build = new LookupCommandWidget.Command.Snippet({name: 'build'});
          var rake = new LookupCommandWidget.Command.Snippet({name: 'rake'});
          var callback = jasmine.createSpy('callback');

          new LookupCommandWidget.controller({}).searchSnippets('scp', callback);
          deferred.resolve([build, rake]);

          expect(callback).toHaveBeenCalledWith(['build', 'rake']);
        });

        it('should call the textcomplete callback with empty array on failure of lookup', function () {
          var callback = jasmine.createSpy('callback');

          new LookupCommandWidget.controller({}).searchSnippets('scp', callback);
          deferred.reject();

          expect(callback).toHaveBeenCalledWith([]);
        });
      });
    });

    describe('Command.Snippets', function () {
      var snippets;
      beforeEach(function(){
        var build   = new LookupCommandWidget.Command.Snippet({name: 'build'});
        var rake    = new LookupCommandWidget.Command.Snippet({name: 'rake'});
        var ansible = new LookupCommandWidget.Command.Snippet({name: 'ansible'});
        var curl    = new LookupCommandWidget.Command.Snippet({name: 'curl'});
        snippets = new LookupCommandWidget.Command.Snippets([build, rake, ansible, curl]);
      });

      describe('findByName', function () {
        it('should return a snippet matching the name', function () {
          var snippet = snippets.findByName('ansible');

          expect(snippet.name()).toBe('ansible');
        });

        describe('allNames', function () {
          it('should have names of all the snippets', function () {
            var names = snippets.allNames();

            expect(names).toEqual(['build', 'rake', 'ansible', 'curl']);
          });
        });
      });
    });

    describe('Command.lookup', function () {
      var requestArgs;

      beforeEach(function () {
        spyOn(m, 'request');
        LookupCommandWidget.Command.lookup('rake');

        requestArgs = m.request.calls.mostRecent().args[0];
      });

      it('should get snippets from admin_command_snippets url', function () {
        expect(requestArgs.method).toBe('GET');
        expect(requestArgs.url).toBe('/go/api/admin/command_snippets?prefix=rake')
      });

      it('should post required headers', function () {
        var xhr = jasmine.createSpyObj(xhr, ['setRequestHeader']);
        requestArgs.config(xhr);

        expect(xhr.setRequestHeader).toHaveBeenCalledWith("Content-Type", "application/json");
        expect(xhr.setRequestHeader).toHaveBeenCalledWith("Accept", "application/vnd.go.cd.v1+json");
      });

      it('should unwrap the response data to return list of snippets', function () {
        var snippets = {_embedded: {command_snippets: ['snippet']}};

        expect(requestArgs.unwrapSuccess(snippets)).toEqual(['snippet']);
      });
    });
  });
});


text:
'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var sapx = require( './sapx.js' );
var ndarray = require( './ndarray.js' );

// MAIN //

setReadOnly( sapx, 'ndarray', ndarray );

// EXPORTS //

module.exports = sapx;


text:
//
// GData.h
//

#import "GDataFramework.h"

// utility classes
#import "GDataDateTime.h"
#import "GDataHTTPFetcher.h"
#import "GDataHTTPFetcherLogging.h"
#import "GDataProgressMonitorInputStream.h"
#import "GDataGatherInputStream.h"
#import "GDataMIMEDocument.h"

// base classes
#import "GDataObject.h"
#import "GDataEntryBase.h"
#import "GDataFeedBase.h"
#import "GDataEntryEvent.h"
#import "GDataFeedEvent.h"
#import "GDataEntryMessage.h"
#import "GDataFeedMessage.h"
#import "GDataServiceBase.h"
#import "GDataServiceGoogle.h"
#import "GDataQuery.h"

// standard elements
#import "GDataCategory.h"
#import "GDataComment.h"
#import "GDataEmail.h"
#import "GDataEntryLink.h"
#import "GDataExtendedProperty.h"
#import "GDataFeedLink.h"
#import "GDataGenerator.h"
#import "GDataGeoPt.h"
#import "GDataIM.h"
#import "GDataLink.h"
#import "GDataMoney.h"
#import "GDataOriginalEvent.h"
#import "GDataPerson.h"
#import "GDataPhoneNumber.h"
#import "GDataPostalAddress.h"
#import "GDataRating.h"
#import "GDataRecurrence.h"
#import "GDataRecurrenceException.h"
#import "GDataReminder.h"
#import "GDataTextConstruct.h"
#import "GDataValueConstruct.h"
#import "GDataEntryContent.h"
#import "GDataWhen.h"
#import "GDataWhere.h"
#import "GDataWho.h"
#import "GDataAtomPubControl.h"
#import "GDataBatchID.h"
#import "GDataBatchInterrupted.h"
#import "GDataBatchOperation.h"
#import "GDataBatchStatus.h"

// ACL
#import "GDataACLScope.h"
#import "GDataACLRole.h"
#import "GDataEntryACL.h"
#import "GDataFeedACL.h"

// Media
#import "GDataNormalPlayTime.h"
#import "GDataMediaContent.h"
#import "GDataMediaCategory.h"
#import "GDataMediaCredit.h"
#import "GDataMediaGroup.h"
#import "GDataMediaKeywords.h"
#import "GDataMediaThumbnail.h"
#import "GDataMediaPlayer.h"
#import "GDataMediaRating.h"
#import "GDataMediaRestriction.h"

// Geo
#import "GDataGeo.h"


text:
package no.arktekk.atom.extension.opensearch

import no.arktekk.atom.extension.opensearch.OpensearchConstants._
import no.arktekk.atom.extension.OptionSelectableElementWrapperAtomExtension
import com.codecommit.antixml._
import no.arktekk.atom._

/**
 * @author Erlend Hamnaberg<erlend@hamnaberg.net>
 */
private[opensearch] class IntAtomExtension(name:String) extends OptionSelectableElementWrapperAtomExtension[FeedLike, Int] {
  protected val selector: Selector[Elem] = NSRepr(ns) -> name

  protected def function = (e) => (e \ text).headOption.map(_.toInt).get

  def toChildren(a: Option[Int]) = {
    a.map(x => ElementWrapper.withNameAndText(NamespaceBinding(prefix, ns), name, x.toString)).toIndexedSeq
  }
}


text:
package com.alipay.api.response;

import com.alipay.api.internal.mapping.ApiField;

import com.alipay.api.AlipayResponse;

/**
 * ALIPAY API: alipay.ins.cooperation.region.qrcode.apply response.
 *
 * @author auto create
 * @since 1.0, 2017-10-24 10:29:59
 */
public class AlipayInsCooperationRegionQrcodeApplyResponse extends AlipayResponse {

	private static final long serialVersionUID = 6289567935349529492L;

	/**
	 * 快捷投保产品二维码图片链接URL
	 */
	@ApiField("code_url")
	private String codeUrl;

	public void setCodeUrl(String codeUrl) {
		this.codeUrl = codeUrl;
	}
	public String getCodeUrl( ) {
		return this.codeUrl;
	}

}


text:
"""
    Memory and Disk Noise Filter

    (c) 2015 Massachusetts Institute of Technology
"""

# Native
import argparse
import os
import pickle
import pprint
import sys
import logging
logger = logging.getLogger(__name__)

# LO-PHI

from lophi_analysis.analysis_filter import MemoryFilter
import lophi.globals as G
from memory_analysis import MemoryAnalysis

def main(args):

    logging.basicConfig()

    # debug
    if args.debug:
        logger.setLevel(logging.DEBUG)

    if not args.output_path:
        logger.error("Please specify a filename to save the filters to.")
        sys.exit(0)

    import lophi_automation.database.datastore as datastore
    db_uri = 'mongodb://'+args.db_host+':27017/lophi_db'
    analysis_datastore = datastore.Datastore(db_uri+G.DB_ANALYSES)
    results = analysis_datastore.db.collection.find({'status': 'COMPLETED',
                                                     "machine_type": args.machine_type,
                                                     "analysis_script": args.analysis_script,
                                                     "volatility_profile":
                                                         args.volatility_profile,
                                                     "sample":args.sample_id})

    logger.info("Creating filter from %d analyses..."%results.count())

    # Memory
    mem_filter = MemoryFilter()

    try:
        os.makedirs(args.output_path)
    except:
        pass

    for result in results:
        mem_results = result['memory_analysis']
        logger.info("Memory Filter: Analyzing %s" % result['_id'])

        diff = None

        if not args.rerun and os.path.exists(os.path.join(args.output_path,
                                                          result['_id'] + "_" +
                                                          'mem_diff.txt')):
            diff = pickle.load(open(os.path.join(args.output_path,
                                                 result['_id'] + "_" +
                                                 'mem_diff.txt'), 'rb'))

        else:

            diff = result['memory_analysis']

            pickle.dump(diff, open(os.path.join(args.output_path,
                                                result['_id'] + "_" +
                                                'mem_diff.txt'), 'wb+'))

        if not diff:
            logger.error("Error processing memory analysis for %s . . . skipping!" % result['_id'])
            continue

        mem_filter.add_analysis(diff)

    # adjust the filter
    mem_filter.adjust_filter(1)

    # write filter to disk
    # pprint.pprint(mem_filter.occurrences_dict)
    f = open(os.path.join(args.output_path, 'filter.mem'), 'w')
    f.write(pprint.pformat(mem_filter.occurrences_dict))
    f.close()

if __name__=="__main__":
    # parse args

    parser = argparse.ArgumentParser()

    parser.add_argument("-S", "--db_host", action='store', dest='db_host',
                        default="localhost",
                        help="Database host")

    parser.add_argument("-i", "--sample_id", action='store', dest='sample_id',
                        help="Creates filter from this sample")
    parser.add_argument("-a", action='store', dest='analysis_script',
                        help="Name of analysis that was run")
    parser.add_argument("-T", action='store', dest='machine_type', type=int,
                        help="Machine type for filter")
    parser.add_argument("-p", action='store', dest='volatility_profile',
                        help="Volatility profile")

    parser.add_argument("-o", action='store', dest='output_path',
                        help="Output path to save the filters, e.g. '-o filter' will give 'filter.disk' and 'filter.mem'")

    parser.add_argument("-d", "--debug", action='store_true', dest='debug',
                        help="Debug output")

    parser.add_argument("-r", action='store_true', dest='rerun', default=False,
                    help="Rerun all analyses.")

    args = parser.parse_args()

    main(args)


text:
<?php

namespace Zend\Mail\Protocol\Smtp\Auth;

use Zend\Mail\Protocol\Smtp;

/**
 * Performs LOGIN authentication
 */
class Login extends Smtp
{
    /**
     * LOGIN username
     *
     * @var string
     */
    protected $username;

    /**
     * LOGIN password
     *
     * @var string
     */
    protected $password;

    /**
     * Constructor.
     *
     * @param  string $host   (Default: 127.0.0.1)
     * @param  int    $port   (Default: null)
     * @param  array  $config Auth-specific parameters
     */
    public function __construct($host = '127.0.0.1', $port = null, $config = null)
    {
        // Did we receive a configuration array?
        $origConfig = $config;
        if (is_array($host)) {
            // Merge config array with principal array, if provided
            if (is_array($config)) {
                $config = array_replace_recursive($host, $config);
            } else {
                $config = $host;
            }
        }

        if (is_array($config)) {
            if (isset($config['username'])) {
                $this->setUsername($config['username']);
            }
            if (isset($config['password'])) {
                $this->setPassword($config['password']);
            }
        }

        // Call parent with original arguments
        parent::__construct($host, $port, $origConfig);
    }

    /**
     * Perform LOGIN authentication with supplied credentials
     *
     */
    public function auth()
    {
        // Ensure AUTH has not already been initiated.
        parent::auth();

        $this->_send('AUTH LOGIN');
        $this->_expect(334);
        $this->_send(base64_encode($this->getUsername()));
        $this->_expect(334);
        $this->_send(base64_encode($this->getPassword()));
        $this->_expect(235);
        $this->auth = true;
    }

    /**
     * Set value for username
     *
     * @param  string $username
     * @return Login
     */
    public function setUsername($username)
    {
        $this->username = $username;
        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set value for password
     *
     * @param  string $password
     * @return Login
     */
    public function setPassword($password)
    {
        $this->password = $password;
        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }
}


text:
/*!
 * \file HttpClient.cpp
 * \brief The main HTTP client connection.
 *
 * The worldlib SQL HTTP can make HTTP get requests to remote web servers.
 *
 * \author Russell Toris, WPI - rctoris@wpi.edu
 * \date April 25, 2015
 */

// worldlib
#include "worldlib/remote/HttpClient.h"

// ROS
#include <ros/ros.h>

using namespace std;
using namespace rail::spatial_temporal_learning::worldlib::remote;

HttpClient::HttpClient(const HttpClient &client) : Client(client.getHost(), client.getPort())
{
  // initialize the client
  this->init();
}

HttpClient::HttpClient(const string &host, const uint16_t port) : Client(host, port)
{
  // initialize the client
  this->init();
}

HttpClient::~HttpClient()
{
  // check for an existing connection
  if (curl_ != NULL)
  {
    curl_easy_cleanup(curl_);
  }
}

void HttpClient::init()
{

  // create the base URL
  stringstream ss;
  ss << "http://" << this->getHost() << ":" << this->getPort() << "/";
  base_ = ss.str();

  // initialize cURL
  curl_ = curl_easy_init();
  // follow redirects
  curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1L);
  // set up the read into the buffer
  curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curlWriteFunction);
}

string HttpClient::get(const std::string &url) const
{
  // create the URL
  string full_url = base_ + url;
  curl_easy_setopt(curl_, CURLOPT_URL, full_url.c_str());

  // create a buffer
  string buffer;
  curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &buffer);

  // perform the request and check for errors
  CURLcode result = curl_easy_perform(curl_);
  if (result != CURLE_OK)
  {
    ROS_ERROR("HTTP Error: %s", curl_easy_strerror(result));
    buffer.clear();
  } else
  {
    // check if we had a valid response
    long code;
    curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &code);
    if (code != 200)
    {
      ROS_ERROR("HTTP Error: %s returned Error Code %li.", full_url.c_str(), code);
      buffer.clear();
    }
  }

  return buffer;
}

static size_t rail::spatial_temporal_learning::worldlib::remote::curlWriteFunction(const void *contents,
    const size_t size, const size_t num, void *buffer)
{
  // get the size of contents
  size_t contents_size = size * num;
  // store the result in the buffer
  ((string *) buffer)->append((char *) contents, contents_size);
  return contents_size;
}


text:
from devstack import exceptions as excp
from devstack import log as logging
from devstack import shell as sh

LOG = logging.getLogger("devstack.pip")
PIP_UNINSTALL_CMD_OPTS = ['-y', '-q']
PIP_INSTALL_CMD_OPTS = ['-q']

def _make_pip_name(name, version):
    if version is None:
        return str(name)
    return "%s==%s" % (name, version)

def install(pip, distro):
    name = pip['name']
    root_cmd = distro.get_command('pip')
    LOG.audit("Installing python package (%s) using pip command (%s)" % (name, root_cmd))
    name_full = _make_pip_name(name, pip.get('version'))
    real_cmd = [root_cmd, 'install'] + PIP_INSTALL_CMD_OPTS
    options = pip.get('options')
    if options:
        LOG.debug("Using pip options: %s" % (options))
        real_cmd += [str(options)]
    real_cmd += [name_full]
    sh.execute(*real_cmd, run_as_root=True)

def uninstall(pip, distro, skip_errors=True):
    root_cmd = distro.get_command('pip')
    try:
        # Versions don't seem to matter here...
        name = _make_pip_name(pip['name'], None)
        LOG.audit("Uninstalling python package (%s) using pip command (%s)" % (name, root_cmd))
        cmd = [root_cmd, 'uninstall'] + PIP_UNINSTALL_CMD_OPTS + [name]
        sh.execute(*cmd, run_as_root=True)
    except excp.ProcessExecutionError:
        if skip_errors:
            LOG.debug(("Ignoring execution error that occured when uninstalling pip %s!"
                " (this may be ok if it was uninstalled by a previous component)") % (name))
        else:
            raise


text: ./test/libs/bats/bin/bats test/*.bats


text:
class Order < ActiveRecord::Base
  belongs_to :order_list, validate: true
  belongs_to :purchase_request, validate: true

  validates_associated :order_list, :purchase_request
  validates_presence_of :order_list, :purchase_request
  validates_uniqueness_of :purchase_request_id, scope: :order_list_id

  after_save :reindex
  after_destroy :reindex

  acts_as_list scope: :order_list

  paginates_per 10

  def reindex
    purchase_request.try(:index)
  end
end

# == Schema Information
#
# Table name: orders
#
#  id                  :bigint           not null, primary key
#  order_list_id       :bigint           not null
#  purchase_request_id :bigint           not null
#  position            :integer
#  state               :string
#  created_at          :datetime         not null
#  updated_at          :datetime         not null
#


text:
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script>
    var module = {};
  </script>
  <script src="../index.js"></script>
  <script src="./assertAll.js"></script>

  <script>
    $(document).ready(function () {
      var Type = module.exports;

      var iFrame = document.createElement('IFRAME');
      document.body.appendChild(iFrame);
      var IFrameArray = window.frames[0].Array;
      var array = new IFrameArray();

      try {
        assertAll([
          [array instanceof Array, false, "array from other frame isn't Array"],
          [array instanceof IFrameArray, true, "array from other frame is instance of that frames Array"],
          [Type.of(array), Array, "Type.of(array) is Array"],
          [Type.is(array, Array), false, "Type.is(array, Array) is false (other frame)"],
          [Type.is(array, "Array"), true, "Type.is(array, \"Array\") is true"]
        ]);
        alert('all tests passed');
      } catch (error) {
        alert(error);
      }

    });
  </script>
</head>
<body>
</body>
</html>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>- ДАНАТЕЯ -</title>
    <link href="css/main.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                        д
                        а
                        н
                        а
                        т
                        е
                        я

                        о нас

                        подбор персонала

                        вакансии

                        статьи

                        отзывы

                        д
                        а
                        н
                        а
                        т
                        е
                        я

                        Услуги подбора персонала

                        г. МИНСК  пр-т НЕЗАВИСИМОСТИ, 11 КОРП. 2 ОФИС 317

                        тел.: +375(29)113-05-10; +375(29)753-64-68

домашний персонал

Няня

Домработница

Сиделка

Повар

Личный водитель

Садовник

педагоги

Репетитор

Гувернантка

Логопед

водители, строители

Водитель категории С

Водитель категории E

Личный водитель

Строитель

Связаться с нами

                    manager@danatea.com

                         Vkontakte

                         Facebook

                         Instagram

            Copyright © ДАНАТЕЯ 2017


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

"""

from resource_management.libraries.functions.version import format_hdp_stack_version, compare_versions
from resource_management import *
from resource_management.core.system import System
import json
import collections

config = Script.get_config()
tmp_dir = Script.get_tmp_dir()

hdp_stack_version = str(config['hostLevelParams']['stack_version'])
hdp_stack_version = format_hdp_stack_version(hdp_stack_version)
stack_is_hdp22_or_further = hdp_stack_version != "" and compare_versions(hdp_stack_version, '2.2') >= 0

#users and groups
hbase_user = config['configurations']['hbase-env']['hbase_user']
nagios_user = config['configurations']['nagios-env']['nagios_user']
smoke_user =  config['configurations']['cluster-env']['smokeuser']
gmetad_user = config['configurations']['ganglia-env']["gmetad_user"]
gmond_user = config['configurations']['ganglia-env']["gmond_user"]
tez_user = config['configurations']['tez-env']["tez_user"]

user_group = config['configurations']['cluster-env']['user_group']
proxyuser_group = default("/configurations/hadoop-env/proxyuser_group","users")
nagios_group = config['configurations']['nagios-env']['nagios_group']

hdfs_log_dir_prefix = config['configurations']['hadoop-env']['hdfs_log_dir_prefix']

#hosts
hostname = config["hostname"]
ambari_server_hostname = config['clusterHostInfo']['ambari_server_host'][0]
rm_host = default("/clusterHostInfo/rm_host", [])
slave_hosts = default("/clusterHostInfo/slave_hosts", [])
hagios_server_hosts = default("/clusterHostInfo/nagios_server_host", [])
oozie_servers = default("/clusterHostInfo/oozie_server", [])
hcat_server_hosts = default("/clusterHostInfo/webhcat_server_host", [])
hive_server_host =  default("/clusterHostInfo/hive_server_host", [])
hbase_master_hosts = default("/clusterHostInfo/hbase_master_hosts", [])
hs_host = default("/clusterHostInfo/hs_host", [])
jtnode_host = default("/clusterHostInfo/jtnode_host", [])
namenode_host = default("/clusterHostInfo/namenode_host", [])
zk_hosts = default("/clusterHostInfo/zookeeper_hosts", [])
ganglia_server_hosts = default("/clusterHostInfo/ganglia_server_host", [])
storm_server_hosts = default("/clusterHostInfo/nimbus_hosts", [])
falcon_host =  default('/clusterHostInfo/falcon_server_hosts', [])

has_sqoop_client = 'sqoop-env' in config['configurations']
has_namenode = not len(namenode_host) == 0
has_hs = not len(hs_host) == 0
has_resourcemanager = not len(rm_host) == 0
has_slaves = not len(slave_hosts) == 0
has_nagios = not len(hagios_server_hosts) == 0
has_oozie_server = not len(oozie_servers)  == 0
has_hcat_server_host = not len(hcat_server_hosts)  == 0
has_hive_server_host = not len(hive_server_host)  == 0
has_hbase_masters = not len(hbase_master_hosts) == 0
has_zk_host = not len(zk_hosts) == 0
has_ganglia_server = not len(ganglia_server_hosts) == 0
has_storm_server = not len(storm_server_hosts) == 0
has_falcon_server = not len(falcon_host) == 0
has_tez = 'tez-site' in config['configurations']

is_namenode_master = hostname in namenode_host
is_jtnode_master = hostname in jtnode_host
is_rmnode_master = hostname in rm_host
is_hsnode_master = hostname in hs_host
is_hbase_master = hostname in hbase_master_hosts
is_slave = hostname in slave_hosts
if has_ganglia_server:
  ganglia_server_host = ganglia_server_hosts[0]

hbase_tmp_dir = config['configurations']['hbase-site']['hbase.tmp.dir']

#security params
security_enabled = config['configurations']['cluster-env']['security_enabled']

#java params
java_home = config['hostLevelParams']['java_home']
artifact_dir = format("{tmp_dir}/AMBARI-artifacts/")
jdk_name = default("/hostLevelParams/jdk_name", None)
# None when jdk is already installed by user
jce_policy_zip = default("/hostLevelParams/jce_name", None)
# None when jdk is already installed by user
jce_location = config['hostLevelParams']['jdk_location']
jdk_location = config['hostLevelParams']['jdk_location']
java_profile_location = "/etc/profile.d/java.sh"
ignore_groupsusers_create = default("/configurations/cluster-env/ignore_groupsusers_create", False)

smoke_user_dirs = format("/tmp/hadoop-{smoke_user},/tmp/hsperfdata_{smoke_user},/home/{smoke_user},/tmp/{smoke_user},/tmp/sqoop-{smoke_user}")
if has_hbase_masters:
  hbase_user_dirs = format("/home/{hbase_user},/tmp/{hbase_user},/usr/bin/{hbase_user},/var/log/{hbase_user},{hbase_tmp_dir}")
#repo params
repo_info = config['hostLevelParams']['repo_info']
service_repo_info = default("/hostLevelParams/service_repo_info",None)

user_to_groups_dict = collections.defaultdict(lambda:[user_group])
user_to_groups_dict[smoke_user] = [proxyuser_group]
if has_ganglia_server:
  user_to_groups_dict[gmond_user] = [gmond_user]
  user_to_groups_dict[gmetad_user] = [gmetad_user]
if has_tez:
  user_to_groups_dict[tez_user] = [proxyuser_group]

user_to_gid_dict = collections.defaultdict(lambda:user_group)
if has_nagios:
  user_to_gid_dict[nagios_user] = nagios_group

user_list = json.loads(config['hostLevelParams']['user_list'])
group_list = json.loads(config['hostLevelParams']['group_list'])


text:
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201502;

using System;
using System.Collections.Generic;
using System.IO;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201502 {
  /// <summary>
  /// This code example updates the bid of a placement. To get placement, run
  /// GetPlacements.cs.
  ///
  /// Tags: AdGroupCriterionService.mutate
  /// </summary>
  public class UpdatePlacement : ExampleBase {
    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      UpdatePlacement codeExample = new UpdatePlacement();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        long placementId = long.Parse("INSERT_PLACEMENT_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId, placementId);
      } catch (Exception ex) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(ex));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example updates the bid of a placement. To get placement, run " +
            "GetPlacements.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group that contains the placement.
    /// </param>
    /// <param name="placementId">Id of the placement to be updated.</param>
    public void Run(AdWordsUser user, long adGroupId, long placementId) {
      // Get the AdGroupCriterionService.
      AdGroupCriterionService adGroupCriterionService =
          (AdGroupCriterionService) user.GetService(AdWordsService.v201502.AdGroupCriterionService);

      // Since we are not updating any placement-specific fields, it is enough to
      // create a criterion object.
      Criterion criterion = new Criterion();
      criterion.id = placementId;

      // Create ad group criterion.
      BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
      biddableAdGroupCriterion.adGroupId = adGroupId;
      biddableAdGroupCriterion.criterion = criterion;

      // Create the bids.
      BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
      CpmBid cpmBid = new CpmBid();
      cpmBid.bid = new Money();
      cpmBid.bid.microAmount = 1000000;
      biddingConfig.bids = new Bids[] {cpmBid};

      biddableAdGroupCriterion.biddingStrategyConfiguration = biddingConfig;

      // Create the operation.
      AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
      operation.@operator = Operator.SET;
      operation.operand = biddableAdGroupCriterion;

      try {
        // Update the placement.
        AdGroupCriterionReturnValue retVal =
            adGroupCriterionService.mutate(new AdGroupCriterionOperation[] {operation});

        // Display the results.
        if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
          AdGroupCriterion adGroupCriterion = retVal.value[0];
          long bidAmount = 0;
          foreach (Bids bids in (adGroupCriterion as BiddableAdGroupCriterion).
              biddingStrategyConfiguration.bids) {
            if (bids is CpmBid) {
              bidAmount = (bids as CpmBid).bid.microAmount;
              break;
            }
          }
          Console.WriteLine("Placement with ad group id = '{0}', id = '{1}' was updated with " +
              "bid amount = '{2}' micros.", adGroupCriterion.adGroupId,
              adGroupCriterion.criterion.id, bidAmount);
        } else {
          Console.WriteLine("No placement was updated.");
        }
      } catch (Exception ex) {
        throw new System.ApplicationException("Failed to update placement.", ex);
      }
    }
  }
}


text:
import React        from 'react'
import SocialButton from './SocialButton'
import Logo         from './../_assets/svg/LogoFacebook'

export default React.createClass({

  render() {

  	var text = "https://twitter.com";

    return (
    	<SocialButton
    		classes	= "social-button social-button-facebook"
    		post	= { text } >
        	<Logo deltax={250} deltay={250} scale={0.5} />
      	</SocialButton>
    )
  }
})


text:
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved

namespace $namespace.Model
{
    using System.Collections.Generic;

    public class LeaderboardModel
    {
        public LeaderboardModel()
        {
            this.Items = new List<LeaderboardItemModel>();
        }

        public IList<LeaderboardItemModel> Items { get; set; }
    }
}


text:
require 'delegate'
require 'hashie/mash'
require 'yaml'

module Flickxtractr
  class Dotfile < SimpleDelegator

    TEMPLATE_PATH = File.join(File.dirname(__FILE__), '..', '..', 'assets', 'dotfile.yml')
    DOTFILE_FILENAME = ".flickxtractr"

    class << self
      def install
        FileUtils.copy TEMPLATE_PATH, path
      end

      def path
        File.join(user_path, DOTFILE_FILENAME)
      end

      def exists?
        File.exist? path
      end

      private

      def user_path
        Dir.home rescue ENV.fetch('HOME', "/")
      end
    end

    def initialize
      dotfile_path = File.exist?(self.class.path) ? self.class.path : TEMPLATE_PATH
      super Hashie::Mash.new YAML.load_file(dotfile_path)
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/fragment_frame_margin"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="MQTT"
        android:textAllCaps="false"
        android:textSize="@dimen/main_topic_size"
        android:textStyle="italic" />

    <View
        android:id="@+id/view3"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="@dimen/divider_margin_bottom"
        android:layout_marginTop="@dimen/divider_margin_top"
        android:background="@android:color/darker_gray" />

    <EditText
        android:id="@+id/urlEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="URL"
        android:inputType="textUri"
        android:textSize="@dimen/topic_size" />

    <EditText
        android:id="@+id/portEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:digits="0123456789"
        android:ems="10"
        android:hint="Port (default is 1883)"
        android:inputType="number"
        android:maxLength="5"
        android:numeric="integer"
        android:textSize="@dimen/topic_size" />

    <EditText
        android:id="@+id/topicEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Topic"
        android:inputType="textPersonName"
        android:textSize="@dimen/topic_size" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/mqtt_topic_hint"
        android:textSize="@dimen/text_size" />

    <View
        android:id="@+id/view10"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="@dimen/divider_margin_bottom"
        android:layout_marginTop="@dimen/divider_margin_top"
        android:background="@android:color/darker_gray" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="topic structure"
        android:textSize="@dimen/text_size" />

    <Spinner
        android:id="@+id/topic_structure_spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView9"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="data structure"
        android:textSize="@dimen/text_size" />

    <Spinner
        android:id="@+id/data_structure_spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Authentication (Optional) "
            android:textSize="@dimen/text_size"
            android:textStyle="bold" />

        <View
            android:id="@+id/view7"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginBottom="@dimen/divider_margin_bottom"
            android:layout_marginTop="@dimen/divider_margin_top"
            android:layout_weight="1"
            android:background="@android:color/darker_gray" />

    </LinearLayout>

    <EditText
        android:id="@+id/usernameEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Username"
        android:inputType="textPersonName"
        android:textSize="@dimen/topic_size" />

    <EditText
        android:id="@+id/passwordEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        android:textSize="@dimen/topic_size" />

    <Button
        android:id="@+id/add_new_mqtt_action_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add new MQTT broker"
        android:textSize="@dimen/button_text_size" />

</LinearLayout>


text:
import React, { PropTypes } from 'react';
import styles from './Tags.css';

const propTypes = {
  focus: PropTypes.arrayOf(PropTypes.string).isRequired,
  closeHandler: PropTypes.func.isRequired,
};

const Tags = ({ focus, closeHandler }) => (
  <div className={styles.container}>
    {focus.map(name => (
      <span
        className={styles.tag}
        key={name}
      >
        {name}
        <strong
          className={styles.strong}
          onClick={() => closeHandler(name)}
        >
          ×
        </strong>
      </span>
    ))}
  </div>
);

Tags.propTypes = propTypes;

export default Tags;


text:
<?php

function render_template($name, $data = [])
{
    $renderer = \WpPug\Renderer::getInstance();
    echo $renderer->render($name, $data);
}

function get_template_content($name, $data = [])
{
    $renderer = \WpPug\Renderer::getInstance();
    return $renderer->render($name, $data);
}


text:
#include <folly/detail/Iterators.h>

#include <map>

#include <folly/container/Array.h>
#include <folly/portability/GTest.h>

using namespace folly::detail;

namespace {
struct IntArrayIterator
    : IteratorFacade<IntArrayIterator, int const, std::forward_iterator_tag> {
  explicit IntArrayIterator(int const* a) : a_(a) {}
  void increment() { ++a_; }
  int const& dereference() const { return *a_; }
  bool equal(IntArrayIterator const& rhs) const { return rhs.a_ == a_; }
  int const* a_;
};
} // namespace

TEST(IteratorsTest, IterFacadeHasCorrectTraits) {
  using TR = std::iterator_traits<IntArrayIterator>;
  static_assert(std::is_same<TR::value_type, int const>::value, "");
  static_assert(std::is_same<TR::reference, int const&>::value, "");
  static_assert(std::is_same<TR::pointer, int const*>::value, "");
  static_assert(
      std::is_same<TR::iterator_category, std::forward_iterator_tag>::value,
      "");
  static_assert(std::is_same<TR::difference_type, ssize_t>::value, "");
}

TEST(IteratorsTest, SimpleIteratorFacade) {
  static const auto kArray = folly::make_array(42, 43, 44);
  IntArrayIterator end(kArray.data() + kArray.size());
  IntArrayIterator iter(kArray.data());
  EXPECT_NE(iter, end);
  EXPECT_EQ(42, *iter);
  ++iter;
  EXPECT_NE(iter, end);
  EXPECT_EQ(43, *iter);
  ++iter;
  EXPECT_NE(iter, end);
  EXPECT_EQ(44, *iter);
  ++iter;
  EXPECT_EQ(iter, end);
}

namespace {
// Simple iterator adaptor: wraps an int pointer.
struct IntPointerIter : IteratorAdaptor<
                            IntPointerIter,
                            int const*,
                            int const,
                            std::forward_iterator_tag> {
  using Super = IteratorAdaptor<
      IntPointerIter,
      int const*,
      int const,
      std::forward_iterator_tag>;
  explicit IntPointerIter(int const* ptr) : Super(ptr) {}
};
} // namespace

TEST(IteratorsTest, IterAdaptorHasCorrectTraits) {
  using TR = std::iterator_traits<IntPointerIter>;
  static_assert(std::is_same<TR::value_type, int const>::value, "");
  static_assert(std::is_same<TR::reference, int const&>::value, "");
  static_assert(std::is_same<TR::pointer, int const*>::value, "");
  static_assert(
      std::is_same<TR::iterator_category, std::forward_iterator_tag>::value,
      "");
  static_assert(std::is_same<TR::difference_type, ssize_t>::value, "");
}

TEST(IteratorsTest, IterAdaptorWithPointer) {
  static const auto kArray = folly::make_array(42, 43, 44);
  IntPointerIter end(kArray.data() + kArray.size());
  IntPointerIter iter(kArray.data());
  EXPECT_NE(iter, end);
  EXPECT_EQ(42, *iter);
  ++iter;
  EXPECT_NE(iter, end);
  EXPECT_EQ(43, *iter);
  ++iter;
  EXPECT_NE(iter, end);
  EXPECT_EQ(44, *iter);
  ++iter;
  EXPECT_EQ(iter, end);
}

namespace {
// More complex case: wrap a map iterator, but these provide either the key or
// value.
struct IntMapKeyIter : IteratorAdaptor<
                           IntMapKeyIter,
                           std::map<int, int>::iterator,
                           int const,
                           std::forward_iterator_tag> {
  using Super = IteratorAdaptor<
      IntMapKeyIter,
      std::map<int, int>::iterator,
      int const,
      std::forward_iterator_tag>;
  explicit IntMapKeyIter(std::map<int, int>::iterator iter) : Super(iter) {}
  int const& dereference() const { return base()->first; }
};

struct IntMapValueIter : IteratorAdaptor<
                             IntMapValueIter,
                             std::map<int, int>::iterator,
                             int,
                             std::forward_iterator_tag> {
  using Super = IteratorAdaptor<
      IntMapValueIter,
      std::map<int, int>::iterator,
      int,
      std::forward_iterator_tag>;
  explicit IntMapValueIter(std::map<int, int>::iterator iter) : Super(iter) {}
  int& dereference() const { return base()->second; }
};

} // namespace

TEST(IteratorsTest, IterAdaptorOfOtherIter) {
  std::map<int, int> m{{2, 42}, {3, 43}, {4, 44}};

  IntMapKeyIter keyEnd(m.end());
  IntMapKeyIter keyIter(m.begin());
  EXPECT_NE(keyIter, keyEnd);
  EXPECT_EQ(2, *keyIter);
  ++keyIter;
  EXPECT_NE(keyIter, keyEnd);
  EXPECT_EQ(3, *keyIter);
  ++keyIter;
  EXPECT_NE(keyIter, keyEnd);
  EXPECT_EQ(4, *keyIter);
  ++keyIter;
  EXPECT_EQ(keyIter, keyEnd);

  IntMapValueIter valueEnd(m.end());
  IntMapValueIter valueIter(m.begin());
  EXPECT_NE(valueIter, valueEnd);
  EXPECT_EQ(42, *valueIter);
  ++valueIter;
  EXPECT_NE(valueIter, valueEnd);
  EXPECT_EQ(43, *valueIter);
  ++valueIter;
  EXPECT_NE(valueIter, valueEnd);
  EXPECT_EQ(44, *valueIter);
  ++valueIter;
  EXPECT_EQ(valueIter, valueEnd);
}

namespace {
struct IntMapValueIterConst : IteratorAdaptor<
                                  IntMapValueIterConst,
                                  std::map<int, int>::const_iterator,
                                  int const,
                                  std::forward_iterator_tag> {
  using Super = IteratorAdaptor<
      IntMapValueIterConst,
      std::map<int, int>::const_iterator,
      int const,
      std::forward_iterator_tag>;
  explicit IntMapValueIterConst(std::map<int, int>::const_iterator iter)
      : Super(iter) {}
  /* implicit */ IntMapValueIterConst(IntMapValueIter const& rhs)
      : IntMapValueIterConst(rhs.base()) {}
  int const& dereference() const { return base()->second; }
};
} // namespace

TEST(IteratorsTest, MixedConstAndNonconstIters) {
  std::map<int, int> m{{2, 42}, {3, 43}, {4, 44}};
  IntMapValueIterConst cend(m.cend());
  IntMapValueIter valueIter(m.begin());
  EXPECT_NE(valueIter, cend);
  ++valueIter;
  ++valueIter;
  ++valueIter;
  EXPECT_EQ(valueIter, cend);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<string name="low_memory_error">"Δεν ήταν δυνατή η ολοκλήρωση της προηγούμενης λειτουργίας λόγω χαμηλού επιπέδου μνήμης"</string>
<string name="opening_file_error">"Αποτυχ. ανοίγμ. επιλεγμ. αρχείου"</string>
<string name="copy_to_clipboard_failure_message">"Αποτυχία αντιγραφής στο πρόχειρο"</string>
<string name="accessibility_date_picker_month">"Μήνας"</string>
<string name="accessibility_date_picker_year">"Έτος"</string>
<string name="date_picker_dialog_set">"Ορισμός"</string>
<string name="month_picker_dialog_title">"Ορισμός μήνα"</string>
<string name="accessibility_date_picker_week">"Εβδομάδα"</string>
<string name="week_picker_dialog_title">"Ορισμός εβδομάδας"</string>
<string name="time_picker_dialog_am">"π.μ."</string>
<string name="time_picker_dialog_pm">"μ.μ."</string>
<string name="time_picker_dialog_title">"Ορισμός χρόνου"</string>
<string name="accessibility_time_picker_hour">"Ώρα"</string>
<string name="accessibility_time_picker_minute">"Λεπτό"</string>
<string name="accessibility_time_picker_second">"Δευτερόλεπτο"</string>
<string name="accessibility_time_picker_milli">"Χιλιοστό του δευτερολέπτου"</string>
<string name="accessibility_time_picker_ampm">"Π.Μ./Μ.Μ."</string>
<string name="time_picker_dialog_hour_minute_separator">":"</string>
<string name="time_picker_dialog_minute_second_separator">":"</string>
<string name="time_picker_dialog_second_subsecond_separator">"."</string>
<string name="date_time_picker_dialog_title">"Ορισμός ημερομηνίας και ώρας"</string>
<string name="accessibility_datetime_picker_date">"Ημερομηνία"</string>
<string name="accessibility_datetime_picker_time">"Ώρα"</string>
<string name="date_picker_dialog_other_button_label">"Άλλο"</string>
<string name="date_picker_dialog_title">"Ορισμός ημερομηνίας"</string>
<string name="date_picker_dialog_clear">"Διαγραφή"</string>
<string name="photo_picker_select_images">"Επιλέξτε εικόνες"</string>
<string name="photo_picker_camera">"Κάμερα"</string>
<string name="photo_picker_browse">"Περιήγηση"</string>
<string name="autofill_popup_content_description">"Εμφάνιση αναδυόμενου παραθύρου αυτόματης συμπλήρωσης"</string>
<string name="password_generation_popup_content_description">"Εμφάνιση αναδυόμενου παραθύρου δημιουργίας κωδικού πρόσβασης"</string>
<string name="autofill_keyboard_accessory_content_description">"Διαθέσιμες προτάσεις"</string>
<string name="updating_chrome">"Ενημέρωση του Chrome…"</string>
</resources>


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

  url 'https://dl.google.com/dl/androidjumper/mtp/current/androidfiletransfer.dmg'
  homepage 'http://www.android.com/filetransfer/'
  license :unknown

  app 'Android File Transfer.app'

  zap :delete => '~/Library/Application Support/Google/Android File Transfer',
      :rmdir  => '~/Library/Application Support/Google/'
end


text:
'use strict';

var ResourceFactory = require('../ResourceFactory');

function makeResourceURL(id) {
    return '/vast-banners/' + id + '/conversion-tag';
};

var ConvTag = function(adbutler) {
    return ResourceFactory.makeResource.call(adbutler, makeResourceURL, {
        create: false,
        update: false,
        delete: false,
        list: false,
    });
};

// Custom Resource Methods
// ConvTag.customMethod1 = function() {};
// ConvTag.customMethod2 = function() {};

module.exports = ConvTag;


text:
class TT_Tractor : public chrono::vehicle::ChWheeledVehicle {
  public:
    TT_Tractor(const bool fixed,
               chrono::vehicle::SuspensionType suspType,
               chrono::ChMaterialSurface::ContactMethod contactMethod = chrono::ChMaterialSurface::NSC);

    ~TT_Tractor() {}

    virtual int GetNumberAxles() const override { return 2; }

    double GetSpringForce(const chrono::vehicle::WheelID& wheel_id) const;
    double GetSpringLength(const chrono::vehicle::WheelID& wheel_id) const;
    double GetSpringDeformation(const chrono::vehicle::WheelID& wheel_id) const;

    double GetShockForce(const chrono::vehicle::WheelID& wheel_id) const;
    double GetShockLength(const chrono::vehicle::WheelID& wheel_id) const;
    double GetShockVelocity(const chrono::vehicle::WheelID& wheel_id) const;

    virtual void Initialize(const chrono::ChCoordsys<>& chassisPos, double chassisFwdVel = 0) override;

    // Log debugging information
    void LogHardpointLocations();  /// suspension hardpoints at design
    void DebugLog(int what);       /// shock forces and lengths, constraints, etc.

  private:
    chrono::vehicle::SuspensionType m_suspType;
};

#endif


text:
<?php

namespace Laradic\Generators\Core\Elements;

class UseTraitElement extends Element
{

    /** @var string */
    protected $name;

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

    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     * @return $this
     */
    public function setName($name)
    {
        $this->name = (string) $name;
        return $this;
    }

    public function toLines()
    {
        return sprintf('use %s;', $this->name);
    }
}


text:
class Rest::AccountsController < Rest::RestController

 before_filter :validate_rest_call
 before_filter :check_ids
 before_filter :check_relationships

  # GET accounts/1
  # GET accounts/1.xml
  # GET accounts/1.json
  def show
    begin
      @resource = Account.find(params[:id])
      render :response => :GET
    rescue Exception => e
      @error = process_exception(e)
      render :response => :error
    end
  end

  # GET accounts/
  # GET accounts.xml
  # GET accounts.json
  def index
    begin

    @parcel = get_paginated_records_for(
      :for            => Account,
      :start_index    => params[:start_index],
      :max_results    => params[:max_results],
      :order_by       => params[:order_by],
      :direction      => params[:direction],
      :conditions     => params[:conditions]
      )
      render :response => :GETALL
    rescue Exception => e
      @error = process_exception(e)
      render :response => :error
    end

  end

  # POST accounts/
  def create
    begin
      @resource = Account.new(params[:account])
      @resource.save!
      render :response => :POST
    rescue Exception => e
      @error = process_exception(e)
      render :response => :error
    end
  end

  # DONE!
  # PUT accounts/id
  # PUT accounts/id.xml
  # PUT accounts/id.json
  def update
    begin
      @resource = Account.find(params[:id])
      @resource.update_attributes!(params[:account])
      render :response => :PUT
    rescue Exception => e
      @error = process_exception(e)
      render :response => :error
    end
  end

  # DELETE accounts/id
  # DELETE accounts/id.xml
  # DELETE accounts/id.json
  def destroy

    begin
      destroy_item(Account, params[:id], params[:lock_version])
      render :response => :DELETE
    rescue Exception => e
      @error = process_exception(e)
      render :response => :error
    end
  end

  protected

  def validate_rest_call

    if %w{create update}.include? params[:action]
      render :json => report_errors(nil, 'Provide account resource to be created/updated')[0],
        :status => 400 and return false if !params[:account]
      begin
        params[:account] = JSON.parse(params[:account])
        params[:account] = substitute_ids(params[:account])
        check_id_conflict(params[:account], params[:id])
        valid_account?(params[:account], params)
      rescue MadbException => e
        render :json => report_errors(nil, e)[0], :status => e.code and return false
      rescue Exception => e
        render :json => report_errors(nil, e)[0], :status => 400 and return false
      end

    end

    if params[:action] == 'destroy'
      render :json => report_errors(nil, 'Provide lock_version for update/delete operations')[0],
        :status => 400 and return false if !params[:lock_version]
    end

    return true;
  end

  def check_ids

    if params[:id]
      render :json => report_errors(nil, "Account[#{params[:id]}] does not exists")[0],
        :status => 404 and return false if !Account.exists?(params[:id].to_i)
    end

    if params[:account]
      render :json => report_errors(nil,"AccountType[#{params[:account][:account_type_id]}] does not exists")[0],
        :status => 404 and return false if !AccountType.exists?(params[:account][:account_type_id])
    end

    return true
  end

  def check_relationships
    begin
      belongs_to_user?(session['user'],
                    :account => params[:id])
    rescue MadbException => e
      render :json => report_errors(nil, e)[0], :status => 400 and return false
    end
  end

  protected
 # Overriden from LoginSystem in order to render custom message
  def access_denied
    render :json => %Q~{"errors": ["Please login to consume the REST API"]}~, :status => 401
  end

end


text:
=head1 LICENSE

Copyright [2009-2014] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=head1 NAME

Bio::EnsEMBL::EGPipeline::PostCompara::RunnableDB::GOProjectionSourceFactory;

=head1 DESCRIPTION

=head1 AUTHOR

ckong

=cut
package Bio::EnsEMBL::EGPipeline::PostCompara::RunnableDB::GOProjectionSourceFactory;

use strict;
use Data::Dumper;
use Bio::EnsEMBL::Registry;
use base ('Bio::EnsEMBL::EGPipeline::PostCompara::RunnableDB::Base');

sub fetch_input {
    my ($self) 	= @_;

    my $go_config = $self->param_required('go_config') || die "'go_config' is an obligatory parameter";
    $self->param('go_config', $go_config);

return 0;
}

sub write_output {
    my ($self)  = @_;

    my $go_config = $self->param('go_config');

    foreach my $pair (keys $go_config){
       my $source                 = $go_config->{$pair}->{'source'};
       my $species                = $go_config->{$pair}->{'species'};
       my $antispecies            = $go_config->{$pair}->{'antispecies'};
       my $division               = $go_config->{$pair}->{'division'};
       my $run_all                = $go_config->{$pair}->{'run_all'};
       my $method_link_type       = $go_config->{$pair}->{'go_method_link_type'};
       my $homology_types_allowed = $go_config->{$pair}->{'go_homology_types_allowed'};
       my $percent_id_filter      = $go_config->{$pair}->{'go_percent_id_filter'};
       my $ensemblObj_type        = $go_config->{$pair}->{'ensemblObj_type'};
       my $ensemblObj_type_target = $go_config->{$pair}->{'ensemblObj_type_target'};

      $self->dataflow_output_id(
		{'source'      		  => $source,
		 'species'     		  => $species,
		 'antispecies' 		  => $antispecies,
  		 'division'    	  	  => $division,
		 'run_all' 		  => $run_all,
		 'method_link_type' 	  => $method_link_type,
                 'homology_types_allowed' => $homology_types_allowed,
  		 'percent_id_filter'      => $percent_id_filter,
		 'ensemblObj_type'        => $ensemblObj_type,
		 'ensemblObj_type_target' => $ensemblObj_type_target
		},2);
      }

return 0;
}

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

return 0;
}

1;


text:
    Apache License

    Version 2.0, January 2004

        DelayedProgress

        Copyright (C) 2015 Said Tahsin Dane

        Timber

        Copyright 2013 Jake Wharton

        App Intro

        Copyright 2015 PaoloRotolo

        RtlViewPager

        Copyright 2016 Duolingo

        OkHttp

        Copyright 2012 Square

        Dagger 2

        Copyright 2012 The Dagger Authors

        RxJava 2

        Copyright (c) 2016-present, RxJava Contributors.

        RxAndroid 2

        Copyright 2015 The RxAndroid authors

        Kotlin

        Copyright 2010-2018 JetBrains s.r.o.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
# Profile Picture

[![Build Status](https://travis-ci.org/xenomuta/profile-pic.png?branch=master)](https://travis-ci.org/xenomuta/profile-pic)

Create cover and profile pictures with face centered and uniform expected sizes.

It gets an input image and outputs three images: a cover image centered with specified size in landscape and portrait, and a profile picture with square ratio centered in bigest detected human face.

## Install

```bash
npm install profile-pic
```

## Usage

```javascript
var profilePic = require('profile-pic');
var images = [
    /* Landscape Ratio */
    {
        width: 400,
        height: 240,
        filename: '/tmp/landscape.jpg'
    },
    /* Portrait Ratio */
    {
        width: 240,
        height: 400,
        filename: '/tmp/standing.jpg'
    },
    /* detected face avatar with square ratio */
    {
        avatar: true,
        width: 128,
        height: 128,
        filename: '/tmp/profile.jpg'
    }
];

profilePic('./test-image.jpeg', images)
    .then(function (result) {
		/*
		[ { width: 400, height: 240, filename: '/tmp/landscape.jpg' },
		  { width: 240, height: 400, filename: '/tmp/standing.jpg' },
		  { avatar: true,
		    width: 128,
		    height: 128,
		    filename: '/tmp/profile.jpg',
		    faces: 5 } ]
		*/
    })
    .catch(function (err) {
        // Something bad happened ...
    });
```

This example will result in 3 images out of this input:

**INPUT**:

**OUTPUT**:
- Two centered and resized to expected size:

landscape.jpg (400x240)

standing.jpg (400x240)

- And one avatar image with biggest detected face:

profile.jpg (128x128)


text:
<?php
declare(strict_types=1);

namespace App\Service\Meetup;

use App\Entity\Meetup;
use Doctrine\ORM\EntityManagerInterface;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

/**
 * @codeCoverageIgnore
 */
final class FindMeetupByUuidFactory implements FactoryInterface
{
    public function __invoke(
        ContainerInterface $container,
        $requestedName,
        array $options = null
    ) : FindMeetupByUuidInterface {
        return new DoctrineFindMeetupByUuid(
            $container->get(EntityManagerInterface::class)->getRepository(Meetup::class)
        );
    }
}


text:
layout: post
title: "扭扭车"
date: 2019-03-10
excerpt: "妍妍的日记-106"
tags: [徐晓妍]
feature: https://static.justice-love.com/image/jpg/xktp.jpg
yan: true
comments: true
video: true
---
妈妈带着妍妍在车库玩,现在妍妍已经可以自如的开着她的扭扭车到处走了😊
{: .notice}
<video id="my-video" class="video-js vjs-16-9 clipboard" controls preload="auto" width="722" height="264" data-setup="{}">
    <source src="{{ site.staticUrl }}/yanyan/video/cknnc.mp4" type='video/mp4'>

      To view this video please enable JavaScript, and consider upgrading to a web browser that
      supports HTML5 video

</video>


text:
import ejs from "ejs";
import fs from "fs";
import path from "path";
import { groupBy } from "lodash";
import { TestReport } from "./testResult";
import { writeContentToFile } from "./fileUtilities";

export enum Format {
   HTML,
}

/**
 * Create Test Result exported file
 */
export async function exportTo(
   format: Format,
   testReport: TestReport,
   filename: string
): Promise<string> {
   switch (format) {
      case Format.HTML:
      default: {
         return exportToHtml(testReport, filename);
      }
   }
}

export async function exportToHtml(
   testReport: TestReport,
   filename: string
): Promise<string> {
   // Group results to faciliate HTML export
   const completed = groupBy(
      testReport.testResults.filter(
         result =>
            // The html template requires the presence of the parent feature (with no scenario name)
            // whenever a scenario is completed
            (result.scenarioName === "" && result.isRequired) ||
            (!!result.scenarioName && result.isRequired && result.isCompleted)
      ),
      "groupedFeatureName"
   );

   const todo = groupBy(
      testReport.testResults.filter(
         // only include feature that contain required scenarios
         result =>
            !!result.scenarioName && result.isRequired && !result.isCompleted
      ),
      "groupedFeatureName"
   );

   const notRequired = groupBy(
      testReport.testResults.filter(result => !result.isRequired),
      "groupedFeatureName"
   );

   const INDEX_FILE = path.join(__dirname, "ejs", "index.ejs");
   const template = fs.readFileSync(INDEX_FILE, "utf-8");

   const data = {
      completed: completed,
      todo: todo,
      notRequired: notRequired,
      versionToTest: testReport.versionToTest,
   };
   const options = {
      filename: INDEX_FILE,
   };

   const htmlContent = ejs.render(template, data, options);

   await writeContentToFile(
      filename.endsWith(".html") ? filename : filename.concat(".html"),
      htmlContent
   );
   return htmlContent;
}


text:
#include "config.h"
#include "GtkPopupMenu.h"

#include "GtkVersioning.h"
#include <gtk/gtk.h>
#include <wtf/gobject/GUniquePtr.h>
#include <wtf/text/CString.h>

namespace WebCore {

static const uint32_t gSearchTimeoutMs = 1000;

GtkPopupMenu::GtkPopupMenu()
    : m_popup(gtk_menu_new())
    , m_previousKeyEventCharacter(0)
    , m_currentlySelectedMenuItem(0)
{
    m_keyPressHandlerID = g_signal_connect(m_popup.get(), "key-press-event", G_CALLBACK(GtkPopupMenu::keyPressEventCallback), this);
}

GtkPopupMenu::~GtkPopupMenu()
{
    g_signal_handler_disconnect(m_popup.get(), m_keyPressHandlerID);
}

void GtkPopupMenu::clear()
{
    gtk_container_foreach(GTK_CONTAINER(m_popup.get()), reinterpret_cast<GtkCallback>(menuRemoveItem), this);
}

void GtkPopupMenu::appendSeparator()
{
    GtkWidget* menuItem = gtk_separator_menu_item_new();
    gtk_menu_shell_append(GTK_MENU_SHELL(m_popup.get()), menuItem);
    gtk_widget_show(menuItem);
}

void GtkPopupMenu::appendItem(GtkAction* action)
{
    GtkWidget* menuItem = gtk_action_create_menu_item(action);
    gtk_widget_set_tooltip_text(menuItem, gtk_action_get_tooltip(action));
    g_signal_connect(menuItem, "select", G_CALLBACK(GtkPopupMenu::selectItemCallback), this);
    gtk_menu_shell_append(GTK_MENU_SHELL(m_popup.get()), menuItem);

    if (gtk_action_is_visible(action))
        gtk_widget_show(menuItem);
}

void GtkPopupMenu::popUp(const IntSize& menuSize, const IntPoint& menuPosition, int itemCount, int selectedItem, const GdkEvent* event)
{
    resetTypeAheadFindState();
    m_menuPosition = menuPosition;
    gtk_menu_set_active(GTK_MENU(m_popup.get()), selectedItem);

    // This approach follows the one in gtkcombobox.c.
    GtkRequisition requisition;
    gtk_widget_set_size_request(m_popup.get(), -1, -1);
#ifdef GTK_API_VERSION_2
    gtk_widget_size_request(m_popup.get(), &requisition);
#else
    gtk_widget_get_preferred_size(m_popup.get(), &requisition, 0);
#endif
    gtk_widget_set_size_request(m_popup.get(), std::max(menuSize.width(), requisition.width), -1);

    if (itemCount) {
        GUniquePtr<GList> children(gtk_container_get_children(GTK_CONTAINER(m_popup.get())));
        int i;
        GList* child;
        for (i = 0, child = children.get(); i < itemCount; i++, child = g_list_next(child)) {
            if (i > selectedItem)
                break;

            GtkWidget* item = GTK_WIDGET(child->data);
            GtkRequisition itemRequisition;
#ifdef GTK_API_VERSION_2
            gtk_widget_get_child_requisition(item, &itemRequisition);
#else
            gtk_widget_get_preferred_size(item, &itemRequisition, 0);
#endif
            m_menuPosition.setY(m_menuPosition.y() - itemRequisition.height);
        }
    } else {
        // Center vertically the empty popup in the combo box area.
        m_menuPosition.setY(m_menuPosition.y() - menuSize.height() / 2);
    }

    guint button = event && event->type == GDK_BUTTON_PRESS ? event->button.button : 1;
    guint32 activateTime = event ? gdk_event_get_time(event) : GDK_CURRENT_TIME;
#ifdef GTK_API_VERSION_2
    gtk_menu_popup(GTK_MENU(m_popup.get()), 0, 0, reinterpret_cast<GtkMenuPositionFunc>(menuPositionFunction), this, button, activateTime);
#else
    gtk_menu_popup_for_device(GTK_MENU(m_popup.get()), event ? gdk_event_get_device(event) : 0, 0, 0,
        reinterpret_cast<GtkMenuPositionFunc>(menuPositionFunction), this, 0, button, activateTime);
#endif

    // Now that the menu has a position, schedule a resize to make sure it's resized to fit vertically in the work area.
    gtk_widget_queue_resize(m_popup.get());
}

void GtkPopupMenu::popDown()
{
    gtk_menu_popdown(GTK_MENU(m_popup.get()));
    resetTypeAheadFindState();
}

void GtkPopupMenu::menuRemoveItem(GtkWidget* widget, GtkPopupMenu* popupMenu)
{
    ASSERT(popupMenu->m_popup);
    gtk_container_remove(GTK_CONTAINER(popupMenu->m_popup.get()), widget);
}

void GtkPopupMenu::menuPositionFunction(GtkMenu*, gint* x, gint* y, gboolean* pushIn, GtkPopupMenu* popupMenu)
{
    *x = popupMenu->m_menuPosition.x();
    *y = popupMenu->m_menuPosition.y();
    *pushIn = true;
}

void GtkPopupMenu::resetTypeAheadFindState()
{
    m_currentlySelectedMenuItem = 0;
    m_previousKeyEventCharacter = 0;
    m_currentSearchString = "";
}

bool GtkPopupMenu::typeAheadFind(GdkEventKey* event)
{
    // If we were given a non-printable character just skip it.
    gunichar unicodeCharacter = gdk_keyval_to_unicode(event->keyval);
    if (!g_unichar_isprint(unicodeCharacter)) {
        resetTypeAheadFindState();
        return false;
    }

    glong charactersWritten;
    GUniquePtr<gunichar2> utf16String(g_ucs4_to_utf16(&unicodeCharacter, 1, 0, &charactersWritten, 0));
    if (!utf16String) {
        resetTypeAheadFindState();
        return false;
    }

    // If the character is the same as the last character, the user is probably trying to
    // cycle through the menulist entries. This matches the WebCore behavior for collapsed
    // menulists.
    bool repeatingCharacter = unicodeCharacter != m_previousKeyEventCharacter;
    if (event->time - m_previousKeyEventTimestamp > gSearchTimeoutMs)
        m_currentSearchString = String(reinterpret_cast<UChar*>(utf16String.get()), charactersWritten);
    else if (repeatingCharacter)
        m_currentSearchString.append(String(reinterpret_cast<UChar*>(utf16String.get()), charactersWritten));

    m_previousKeyEventTimestamp = event->time;
    m_previousKeyEventCharacter = unicodeCharacter;

    // Like the Chromium port, we case fold before searching, because
    // strncmp does not handle non-ASCII characters.
    GUniquePtr<gchar> searchStringWithCaseFolded(g_utf8_casefold(m_currentSearchString.utf8().data(), -1));
    size_t prefixLength = strlen(searchStringWithCaseFolded.get());

    GList* children = gtk_container_get_children(GTK_CONTAINER(m_popup.get()));
    if (!children)
        return true;

    // If a menu item has already been selected, start searching from the current
    // item down the list. This will make multiple key presses of the same character
    // advance the selection.
    GList* currentChild = children;
    if (m_currentlySelectedMenuItem) {
        currentChild = g_list_find(children, m_currentlySelectedMenuItem);
        if (!currentChild) {
            m_currentlySelectedMenuItem = 0;
            currentChild = children;
        }

        // Repeating characters should iterate.
        if (repeatingCharacter) {
            if (GList* nextChild = g_list_next(currentChild))
                currentChild = nextChild;
        }
    }

    GList* firstChild = currentChild;
    do {
        currentChild = g_list_next(currentChild);
        if (!currentChild)
            currentChild = children;

        GUniquePtr<gchar> itemText(g_utf8_casefold(gtk_menu_item_get_label(GTK_MENU_ITEM(currentChild->data)), -1));
        if (!strncmp(searchStringWithCaseFolded.get(), itemText.get(), prefixLength)) {
            gtk_menu_shell_select_item(GTK_MENU_SHELL(m_popup.get()), GTK_WIDGET(currentChild->data));
            break;
        }
    } while (currentChild != firstChild);

    g_list_free(children);
    return true;
}

void GtkPopupMenu::selectItemCallback(GtkMenuItem* item, GtkPopupMenu* popupMenu)
{
    popupMenu->m_currentlySelectedMenuItem = GTK_WIDGET(item);
}

gboolean GtkPopupMenu::keyPressEventCallback(GtkWidget*, GdkEventKey* event, GtkPopupMenu* popupMenu)
{
    return popupMenu->typeAheadFind(event);
}

} // namespace WebCore


text:
class HomeController < ApplicationController

    #requerido para devise
    before_filter :authenticate_user!, only: [:index, :new]

    def index
    end

    def new

    end

    def edit

    end
end


text:
#ifndef _PEAKELPICKER_HPP_
#define _PEAKELPICKER_HPP_

#include "PeakelPicker.hpp"
#include "MZRTField.hpp"
#include "pwiz/utility/misc/Export.hpp"

namespace pwiz {
namespace analysis {

///
/// interface for picking Peakels and arranging into Features;
///   note: Peakels are actually removed from the PeakelField
///
class PWIZ_API_DECL PeakelPicker
{
    public:

    virtual void pick(PeakelField& peakels, FeatureField& features) const = 0;

    virtual ~PeakelPicker(){}
};

///
/// basic implementation
///
class PWIZ_API_DECL PeakelPicker_Basic : public PeakelPicker
{
    public:

    struct Config
    {
        std::ostream* log;
        size_t minCharge;
        size_t maxCharge;
        size_t minMonoisotopicPeakelSize;
        MZTolerance mzTolerance;
        double rtTolerance;
        size_t minPeakelCount;

        //double intensityThreshold; // ? // some kind of tolerance to match isotope envelope
        //double relativeIntensityTolerance;

        Config()
        :   log(0),
            minCharge(2),
            maxCharge(5),
            minMonoisotopicPeakelSize(3),
            mzTolerance(10, MZTolerance::PPM),
            rtTolerance(5), // seconds
            minPeakelCount(3)
        {}
    };

    PeakelPicker_Basic(const Config& config = Config()) : config_(config) {}

    virtual void pick(PeakelField& peakels, FeatureField& features) const;

    private:
    Config config_;
};

} // namespace analysis
} // namespace pwiz

#endif // _PEAKELPICKER_HPP_


text:
mkdir -p ~/abc/github

for I in $(curl -s https://api.github.com/users/jammycakes/repos | jq -r .[].name)
do
    if [ -e ~/abc/github/$I ]; then
        echo Already cloned $I
    else
        git clone git@github.com:jammycakes/$I ~/abc/github/$I
    fi
done


text:
package org.broadinstitute.hellbender.tools.picard.illumina.parser;

import htsjdk.samtools.util.CloserUtil;
import htsjdk.samtools.util.RuntimeIOException;
import htsjdk.samtools.util.StringUtil;

import org.broadinstitute.hellbender.utils.UnsignedTypeUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;

import static htsjdk.samtools.util.CloserUtil.close;
import static htsjdk.samtools.util.StringUtil.bytesToString;
import static htsjdk.samtools.util.StringUtil.stringToBytes;
import static java.nio.ByteBuffer.allocate;
import static java.nio.ByteOrder.LITTLE_ENDIAN;
import static java.nio.channels.FileChannel.MapMode;
import static java.nio.channels.FileChannel.MapMode.READ_ONLY;
import static org.broadinstitute.hellbender.tools.picard.illumina.parser.IntensityChannel.values;
import static org.broadinstitute.hellbender.utils.UnsignedTypeUtil.uShortToInt;

/**
 * Read a .cnf (binary noise) or .cif (binary intensity) file.  A file in this format contains
 * 1 or more cycles of data for a set of clusters, with 4 values per cycle, one for each channel.
 * A file can store its values in either a byte or a short per value, but the API treats them all as shorts.
 * This class does not distinguish btw CIF and CNF files.
 *
 * @author jburke@broadinstitute.org
 */
class ClusterIntensityFileReader {

    private static final byte[] IDENTIFIER = stringToBytes("CIF");
    private static final byte FILE_VERSION = 1;
    private static final int HEADER_SIZE = 13;
    private static final int NUM_CHANNELS = values().length;

    // Just for error reporting
    private final File file;

    /**
     * The entire file is mmapped
     */
    private final MappedByteBuffer buf;
    private final ClusterIntensityFileHeader header;

    // Precomputed for speed, I hope.
    private final int cycleSize;
    private final int channelSize;

    public static class ClusterIntensityFileHeader {
        public final int elementSize;
        public final int firstCycle;
        public final int numCycles;
        public final int numClusters;

        public ClusterIntensityFileHeader(final byte[] headerBytes, final File file) {
            if (headerBytes.length < HEADER_SIZE) {
                throw new IlluminaParserException("Bytes past to header constructor are too short excpected(" + HEADER_SIZE + ") received (" + headerBytes.length);
            }

            ByteBuffer buf = allocate(headerBytes.length); //for doing some byte conversions
            buf.order(LITTLE_ENDIAN);
            buf.put(headerBytes);
            buf.position(0);

            final byte[] identifierBuf = new byte[IDENTIFIER.length];
            buf.get(identifierBuf);
            if (!Arrays.equals(identifierBuf, IDENTIFIER)) {
                throw new IlluminaParserException("Cluster intensity file " + file + " contains unexpected header: " +
                        bytesToString(identifierBuf));
            }
            final byte fileVersion = buf.get();
            if (fileVersion != FILE_VERSION) {
                throw new IlluminaParserException("Cluster intensity file " + file + " contains unexpected version: " + fileVersion);
            }
            elementSize = buf.get();
            if (elementSize < 1 || elementSize > 2) {
                throw new IlluminaParserException("Cluster intensity file " + file + " contains unexpected element size: " + elementSize);
            }
            // convert these to unsigned
            firstCycle = uShortToInt(buf.getShort());
            numCycles = uShortToInt(buf.getShort());
            if (numCycles == 0) {
                throw new IlluminaParserException("Cluster intensity file " + file + " has zero cycles.");
            }
            numClusters = buf.getInt();
            if (numClusters < 0) {
                // It is possible for there to be no clusters in a tile.
                throw new IlluminaParserException("Cluster intensity file " + file + " has negative number of clusters: " + numClusters);
            }
        }
    }

    /**
     * Prepare to parse a CIF or CNF file.
     *
     * @param file The file to be parsed.
     */
    public ClusterIntensityFileReader(final File file) {
        try {
            this.file = file;
            final FileInputStream is = new FileInputStream(this.file);
            final FileChannel channel = is.getChannel();
            final long fileSize = channel.size();
            buf = channel.map(READ_ONLY, 0, fileSize);
            buf.order(LITTLE_ENDIAN);
            close(channel);
            close(is);
            final byte[] headerBytes = new byte[HEADER_SIZE];
            buf.get(headerBytes);
            this.header = new ClusterIntensityFileHeader(headerBytes, this.file);
        } catch (IOException e) {
            throw new RuntimeIOException("IOException opening cluster intensity file " + file, e);
        }
        cycleSize = NUM_CHANNELS * header.numClusters * header.elementSize;
        channelSize = header.numClusters * header.elementSize;
    }

    /**
     * Get the value for the given args.  Value is returned as a signed short regardless of whether storage is
     * in bytes or shorts.
     *
     * @param cluster 0-based cluster number.
     * @param channel Which channel is desired.
     * @param cycle   Absolute cycle number.  E.g. if the first cycle in the file is N, then the first value that can
     *                be fetched is cycle=N
     * @return Intensity or noise (depending on whether this is a CIF or CNF file).
     */
    public short getValue(final int cluster, final IntensityChannel channel, final int cycle) {
        if (cycle < header.firstCycle || cycle >= header.firstCycle + header.numCycles) {
            throw new IllegalArgumentException("Requested cycle (" + cycle + ") number out of range.  First cycle=" +
                    header.firstCycle + "; numCycles=" + header.numCycles);
        }
        if (cluster < 0 || cluster >= header.numClusters) {
            throw new IllegalArgumentException("Requested cluster (" + cluster + ") number out of range. numClustersInTile=" + header.numClusters);
        }
        final int relativeCycle = cycle - header.firstCycle;
        final int position = HEADER_SIZE + relativeCycle * cycleSize + channel.ordinal() * channelSize + cluster * header.elementSize;
        buf.position(position);
        if (header.elementSize == 1) {
            return buf.get();
        } else {
            return buf.getShort();
        }
    }

    public File getFile() {
        return file;
    }

    /**
     * @return The first (one-based) cycle stored in this file.
     */
    public int getFirstCycle() {
        return header.firstCycle;
    }

    /**
     * @return Number of clusters stored in this file.
     */
    public int getNumClusters() {
        return header.numClusters;
    }

    /**
     * @return Number of cycles stored in this file.
     */
    public int getNumCycles() {
        return header.numCycles;
    }

    /**
     * @return the size of one intensity value for one channel in this file.
     */
    public int getElementSize() {
        return header.elementSize;
    }

    public static ClusterIntensityFileHeader readHeaders(final File intensityFile) {
        FileInputStream reader = null;
        byte[] headerBytes = new byte[HEADER_SIZE];
        int bytesRead = 0;
        try {
            reader = new FileInputStream(intensityFile);
            bytesRead = reader.read(headerBytes);
        } catch (FileNotFoundException fnfExc) {
            throw new IlluminaParserException("Error opening intensity file (" + intensityFile.getAbsolutePath() + ")", fnfExc);
        } catch (IOException ioExc) {
            throw new IlluminaParserException("Error reading values from header for intensity file (" + intensityFile.getAbsolutePath() + ")", ioExc);
        } finally {
            close(reader);
        }

        if (bytesRead != HEADER_SIZE)
            throw new IlluminaParserException("Error reading intensity file header, too few bytes read, expected( " + HEADER_SIZE + ") read(" + bytesRead + ")");

        return new ClusterIntensityFileHeader(headerBytes, intensityFile);
    }
}


text:
<?php

namespace WrapIt\Http;

use WrapIt\Exceptions\WrapItParameterException;

/**
 * Class WrapItPushRequester
 *
 * @package WrapIt
 */
class WrapItPushRequester extends Requester {

    private $access_token = null;

    public function __construct($domain, $token) {
        $this->domain = $domain;
        $this->access_token = $token;
    }

    public function get($api, $data = array()) {
        throw new WrapItParameterException("GET not alowed with this requester");
    }

    public function post($api, $data) {
        $api = ltrim($api, "/");
        return $this->request(array(
            "url" => "https://" . $this->domain . "/" . $api,
            "post" => $data,
            "body_type" => "applicaton/json",
            "headers" => array(
                "Authorization: Bearer " . $this->access_token
            )
        ));
    }

}


text:
<!DOCTYPE html>

	<meta name="viewport" content="width=device-width">
	<meta name="description" content="Midnight Static is an electronic synth rock band based out of Boston, MA.">
	<meta name="keywords" content="Midnight Static, Electronic, Synth Rock, Midnight Static Boston, midnight static band, Synthpop">
  <meta property="og:image" content="http://midnightstatic.com/images/band-2.jpg"/>
	<title>Midnight Static - About</title>
	<link href='http://fonts.googleapis.com/css?family=Josefin+Sans:400' rel='stylesheet' type='text/css'>
	<link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,700' rel='stylesheet' type='text/css'>
	<link href="css/main.css" rel="stylesheet" type="text/css">
	<link rel="icon" type="image/png" href="favicon.png">
	<link rel="stylesheet" href="css/font-awesome/css/font-awesome.min.css">

			Home
          Music
          About
          Shows
          Contact
          Photos

MENU

Home

Music

About

Shows

Contact

Photos

About Midnight Static

Midnight Static is an electronic synth rock band based out of Boston, MA. Filled with layers of catchy melodies and sweeping chord changes, along with nuances of 70's Prog Rock, 80's New Wave and current electronic pop acts such as CHVRCHES and Cut Copy, the music of Midnight Static stirs up moments of nostalgia while hinting at the future of electronic dance rock.

Formed in the winter of 2014 and armed with a handful of songs by songwriter and synth player Steven Borek, Midnight Static were born out of a desire to write engaging electronic dance songs that would get the crowds up on their feet and moving, yet which would retain a pop-rock feel in their intensity and live delivery. "There are so many great guitar based rock bands in and around Boston already and I thought to myself 'Hey, I really like playing rock music, but I don't see a lot of dancing at these shows..." says Borek. "Why not try this with synths instead of guitars and change up the rhythms a bit, and maybe I can get people to enjoy both the energy of rock music and encourage them to dance at the same time?"

As the year 2014 progressed, Borek carefully constructed the band from persons of various musical backgrounds who would each add something special to an already unique sound: the effervescent Jason Kaplan on drums, certified 80's nut Kate Lindsay on synths, the dynamic Jake O'Donnell on bass, and the powerful and engaging voice of vocalist Shannon Spreen.

Midnight Static debuted in January 2015 to a packed house at the Last Safe & Deposit Company in Lowell, MA, and are in the process of recording their first single, "Illusions of the Mind", to be released in late February 2015.

© 2015 Midnight Static. All rights reserved.


text:
<?php

namespace Test\Http\Client;

use GuzzleHttp\Client as GuzzleClient;
use OC\Http\Client\Client;
use OC\Http\Client\ClientService;

/**
 * Class ClientServiceTest
 */
class ClientServiceTest extends \Test\TestCase {
	public function testNewClient() {
		$config = $this->createMock('\OCP\IConfig');
		$certificateManager = $this->createMock('\OCP\ICertificateManager');

		$expected = new Client($config, $certificateManager, new GuzzleClient());
		$clientService = new ClientService($config, $certificateManager);
		$this->assertEquals($expected, $clientService->newClient());
	}
}


text:
DEFAULT_OUI = '00-16-3e'  # Xensource, Inc.

# Returns a random MAC address, with optional +oui+ override
# Note: assumes PRNG seed already suitable. Call `srand` if you care to re-seed.
def random_mac(oui=nil)
  mac_parts = [oui||DEFAULT_OUI]
  [0x7f, 0xff, 0xff].each do |limit|
    mac_parts << "%02x" % rand(limit + 1)
  end
  mac_parts.join('-')
end

if __FILE__==$PROGRAM_NAME
  puts random_mac(ARGV[0])
end