text:
"""
.. moduleauthor:: Gabriel Martin Becedillas Ruiz <gabriel.becedillas@gmail.com>
"""

from pyalgotrade.utils import dt
from pyalgotrade.utils import csvutils
from pyalgotrade.barfeed import membf
from pyalgotrade import dataseries
from pyalgotrade import bar

import datetime
import pytz

# Interface for csv row parsers.
class RowParser(object):
    def parseBar(self, csvRowDict):
        raise NotImplementedError()

    def getFieldNames(self):
        raise NotImplementedError()

    def getDelimiter(self):
        raise NotImplementedError()

# Interface for bar filters.
class BarFilter(object):
    def includeBar(self, bar_):
        raise NotImplementedError()

class DateRangeFilter(BarFilter):
    def __init__(self, fromDate=None, toDate=None):
        self.__fromDate = fromDate
        self.__toDate = toDate

    def includeBar(self, bar_):
        if self.__toDate and bar_.getDateTime() > self.__toDate:
            return False
        if self.__fromDate and bar_.getDateTime() < self.__fromDate:
            return False
        return True

# US Equities Regular Trading Hours filter
# Monday ~ Friday
# 9:30 ~ 16 (GMT-5)
class USEquitiesRTH(DateRangeFilter):
    timezone = pytz.timezone("US/Eastern")

    def __init__(self, fromDate=None, toDate=None):
        DateRangeFilter.__init__(self, fromDate, toDate)

        self.__fromTime = datetime.time(9, 30, 0)
        self.__toTime = datetime.time(16, 0, 0)

    def includeBar(self, bar_):
        ret = DateRangeFilter.includeBar(self, bar_)
        if ret:
            # Check day of week
            barDay = bar_.getDateTime().weekday()
            if barDay > 4:
                return False

            # Check time
            barTime = dt.localize(bar_.getDateTime(), USEquitiesRTH.timezone).time()
            if barTime < self.__fromTime:
                return False
            if barTime > self.__toTime:
                return False
        return ret

class BarFeed(membf.BarFeed):
    """Base class for CSV file based :class:`pyalgotrade.barfeed.BarFeed`.

    .. note::
        This is a base class and should not be used directly.
    """

    def __init__(self, frequency, maxLen=dataseries.DEFAULT_MAX_LEN):
        membf.BarFeed.__init__(self, frequency, maxLen)
        self.__barFilter = None
        self.__dailyTime = datetime.time(0, 0, 0)

    def getDailyBarTime(self):
        return self.__dailyTime

    def setDailyBarTime(self, time):
        self.__dailyTime = time

    def getBarFilter(self):
        return self.__barFilter

    def setBarFilter(self, barFilter):
        self.__barFilter = barFilter

    def addBarsFromCSV(self, instrument, path, rowParser):
        # Load the csv file
        loadedBars = []
        reader = csvutils.FastDictReader(open(path, "r"), fieldnames=rowParser.getFieldNames(), delimiter=rowParser.getDelimiter())
        for row in reader:
            bar_ = rowParser.parseBar(row)
            if bar_ is not None and (self.__barFilter is None or self.__barFilter.includeBar(bar_)):
                loadedBars.append(bar_)

        self.addBarsFromSequence(instrument, loadedBars)

class GenericRowParser(RowParser):
    def __init__(self, columnNames, dateTimeFormat, dailyBarTime, frequency, timezone):
        self.__dateTimeFormat = dateTimeFormat
        self.__dailyBarTime = dailyBarTime
        self.__frequency = frequency
        self.__timezone = timezone
        self.__haveAdjClose = False
        # Column names.
        self.__dateTimeColName = columnNames["datetime"]
        self.__openColName = columnNames["open"]
        self.__highColName = columnNames["high"]
        self.__lowColName = columnNames["low"]
        self.__closeColName = columnNames["close"]
        self.__volumeColName = columnNames["volume"]
        self.__adjCloseColName = columnNames["adj_close"]

    def _parseDate(self, dateString):
        ret = datetime.datetime.strptime(dateString, self.__dateTimeFormat)

        if self.__dailyBarTime is not None:
            ret = datetime.datetime.combine(ret, self.__dailyBarTime)
        # Localize the datetime if a timezone was given.
        if self.__timezone:
            ret = dt.localize(ret, self.__timezone)
        return ret

    def barsHaveAdjClose(self):
        return self.__haveAdjClose

    def getFieldNames(self):
        # It is expected for the first row to have the field names.
        return None

    def getDelimiter(self):
        return ","

    def parseBar(self, csvRowDict):
        dateTime = self._parseDate(csvRowDict[self.__dateTimeColName])
        open_ = float(csvRowDict[self.__openColName])
        high = float(csvRowDict[self.__highColName])
        low = float(csvRowDict[self.__lowColName])
        close = float(csvRowDict[self.__closeColName])
        volume = float(csvRowDict[self.__volumeColName])
        adjClose = None
        if self.__adjCloseColName is not None:
            adjCloseValue = csvRowDict.get(self.__adjCloseColName, "")
            if len(adjCloseValue) > 0:
                adjClose = float(adjCloseValue)
                self.__haveAdjClose = True
        return bar.BasicBar(dateTime, open_, high, low, close, volume, adjClose, self.__frequency)

class GenericBarFeed(BarFeed):
    """A BarFeed that loads bars from CSV files that have the following format:
    ::

        Date Time,Open,High,Low,Close,Volume,Adj Close
        2013-01-01 13:59:00,13.51001,13.56,13.51,13.56,273.88014126,13.51001

    :param frequency: The frequency of the bars. Check :class:`pyalgotrade.bar.Frequency`.
    :param timezone: The default timezone to use to localize bars. Check :mod:`pyalgotrade.marketsession`.
    :type timezone: A pytz timezone.
    :param maxLen: The maximum number of values that the :class:`pyalgotrade.dataseries.bards.BarDataSeries` will hold.
        Once a bounded length is full, when new items are added, a corresponding number of items are discarded from the opposite end.
    :type maxLen: int.

    .. note::
        * The CSV file **must** have the column names in the first row.
        * It is ok if the **Adj Close** column is empty.
        * When working with multiple instruments:

         * If all the instruments loaded are in the same timezone, then the timezone parameter may not be specified.
         * If any of the instruments loaded are in different timezones, then the timezone parameter should be set.
    """

    def __init__(self, frequency, timezone=None, maxLen=dataseries.DEFAULT_MAX_LEN):
        BarFeed.__init__(self, frequency, maxLen)
        self.__timezone = timezone
        # Assume bars don't have adjusted close. This will be set to True after
        # loading the first file if the adj_close column is there.
        self.__haveAdjClose = False

        self.__dateTimeFormat = "%Y-%m-%d %H:%M:%S"
        self.__columnNames = {
            "datetime": "Date Time",
            "open": "Open",
            "high": "High",
            "low": "Low",
            "close": "Close",
            "volume": "Volume",
            "adj_close": "Adj Close",
        }
        # self.__dateTimeFormat expects time to be set so there is no need to
        # fix time.
        self.setDailyBarTime(None)

    def barsHaveAdjClose(self):
        return self.__haveAdjClose

    def setNoAdjClose(self):
        self.__columnNames["adj_close"] = None
        self.__haveAdjClose = False

    def setColumnName(self, col, name):
        self.__columnNames[col] = name

    def setDateTimeFormat(self, dateTimeFormat):
        self.__dateTimeFormat = dateTimeFormat

    def addBarsFromCSV(self, instrument, path, timezone=None):
        """Loads bars for a given instrument from a CSV formatted file.
        The instrument gets registered in the bar feed.

        :param instrument: Instrument identifier.
        :type instrument: string.
        :param path: The path to the CSV file.
        :type path: string.
        :param timezone: The timezone to use to localize bars. Check :mod:`pyalgotrade.marketsession`.
        :type timezone: A pytz timezone.
        """

        if timezone is None:
            timezone = self.__timezone

        rowParser = GenericRowParser(self.__columnNames, self.__dateTimeFormat, self.getDailyBarTime(), self.getFrequency(), timezone)
        BarFeed.addBarsFromCSV(self, instrument, path, rowParser)

        if rowParser.barsHaveAdjClose():
            self.__haveAdjClose = True
        elif self.__haveAdjClose:
            raise Exception("Previous bars had adjusted close and these ones don't have.")


text:
var Content = function(){
    var self = this;

    self.kw_list_html = $('#keywordsWrapper ul');
    self.kw_list_html.extend({
	'_get_kw_html': function(kw, options){
	    var classes = "";

	    if(options != undefined){
		classes = options['classes'] || "";
	    }

	    var score_str = ':' + (kw['score'] == undefined ? '0' : kw['score'].toFixed(2)) + '';
	    var kw_html = $('

' + kw['id'] + score_str + '

') ;
	    kw_html.data('id', kw['id']);
	    kw_html.data('get_internal', function(){
		var lst = self.kws.filter(function(another_kw){
		    return kw['id'] == another_kw['id'];
		});
		return lst[0];
	    });

	    var kw_internal = kw_html.data('get_internal')();

	    kw_internal.update_display = function(doc){
		//if doc is given, update the doc's secondary kewyord display
		//if doc is absent, update the primary keyword display
		if(doc == undefined){
		    kw_html.find('.feedback').text(kw.get_feedback().toFixed(2));
		    if(kw.is_primary_kw_on()){
			kw_html.addClass('text-info');
		    }
		    else{
			kw_html.removeClass('text-info');
		    }
		}
		else{
		    doc.update_kw_display(kw_internal);
		}

	    };
	    return kw_html;
	},
	'add': function(kw, options){
	    this.append(this._get_kw_html(kw, options));
	},
	'reset': function(){
	    this.find('li').remove()
	}
    });

    self.doc_list_html = $('#documentsWrapper ul');
    self.doc_list_html.extend({
	'_get_kw_html': function(kw, doc){
	    var kw2doc_weight = self.kws.filter(function(another_kw){ //find the keyword
		 return another_kw['id'] == kw['id'];
	    })[0]['docs']
		.filter(function(another_doc){ //find the document
		    return another_doc['id'] == doc['id'];
		})[0]['w'];

	    var w_str = ':'+
		kw['w'].toFixed(2) + ',' + kw2doc_weight.toFixed(2)+
		'';
	    var kw2doc_weight = doc['kws'].filter(function(another_kw){
		return another_kw['id'] == kw['id'];
	    })[0]['w'];
	    var kw_html = $('
' + kw['id'] + '' + w_str + '
');
	    kw_html.data('id', kw['id']);
	    kw_html.data('get_internal', function(){//get the associated kw
		var lst = self.kws.filter(function(another_kw){
		    return kw['id'] == another_kw['id'];
		});
		return lst[0];
	    });
	    return kw_html;
	},
	'_get_doc_html': function(doc){
	    var _self =  this;

	    var score_str = ':' +
		(doc['score'] ==  undefined ? '-' : doc['score'].toFixed(2)) +
		'';

	    var html = '

' + doc['title'] + score_str +'
' +
		'

';
	    var doc_html = $(html);

	    doc['kws'].forEach(function(kw){
		var kw_html = _self._get_kw_html(kw, doc);
		doc_html.find('.kws').append(kw_html);
	    })
	    doc_html.data('id', doc['id']);
	    doc_html.data('get_internal', function(){
		var result = self.docs.filter(function(another_doc){
		    return doc['id'] == another_doc['id'];
		});
		return result[0];
	    });

	    var doc_internal = doc_html.data('get_internal')();

	    doc_internal.get_kw_html = function(kw_id){
		//get the kw html
		var kw_html = doc_html.find('.kw').filter(function(idx, kw_html){
		    var kw_html = $(kw_html);
		    return $(kw_html).data('id') == kw_id;
		})[0];

		if(kw_html == undefined){
		    throw "kw_html is undefined with doc_id=" + doc['id'] + ' and kw_id=' + kw_id;
		}
		return $(kw_html);
	    }

	    doc_internal.update_display = function(){
		doc_html.find('.feedback').text(doc.get_feedback().toFixed(2));
	    };

	    doc_internal.highlight_kw = function(kw){
		var kw_html = doc_internal.get_kw_html(kw['id']);
		kw_html.find('.body').removeClass('label-default');
		kw_html.find('.body').addClass('label-info');
	    }

	    doc_internal.underscore_kw = function(kw){
		var kw_html = doc_internal.get_kw_html(kw['id']);
		kw_html.find('.body').css({'text-decoration': 'underline'});
	    }

	    doc_internal.dehighlight_kw = function(kw){
		var kw_html = doc_internal.get_kw_html(kw['id']);
		kw_html.find('.body').addClass('label-default');
		kw_html.find('.body').removeClass('label-info');
	    }

	    doc_internal.deunderscore_kw = function(kw){
		var kw_html = doc_internal.get_kw_html(kw['id']);
		kw_html.find('.body').css({'text-decoration': 'none'});
	    }

	    doc_internal.update_kw_display = function(kw){
		if(kw.is_primary_kw_on()){
		    doc_internal.underscore_kw(kw);
		}
		else{
		    doc_internal.deunderscore_kw(kw);
		}

		if(doc.is_kw_on(kw)){
		    doc_internal.highlight_kw(kw);
		}
		else{
		    doc_internal.dehighlight_kw(kw);
		}

	    };

	    return doc_html;
	},
	'add': function(doc){
	    this.append(this._get_doc_html(doc));
	},
	'reset': function(){
	    this.find('li').remove()
	}
    });

    self.propagate_from_response = function(res){
	//propagate the data from http response to the global variable
	self.session_id = res['session_id'];

	self.docs = res['docs'];

	self.kws = res['kws'];

	self.alpha = 0.7; //parameter controlling the relative weighing of feedback from keyword iteself or document
	self.beta = 0.7;
    }

    self.define_update_rules = function(){
	//extend the functionality of the current keyword
	self.kws.forEach(function(kw){
	    kw._fb_from_doc = 0;
	    kw._fb_from_itself = 0;

	    kw._doc2weight = {};
	    kw['docs'].forEach(function(doc){
		kw._doc2weight[doc['id']] = doc['w'];
	    });

	    kw._doc_weights = [];
	    $.each(kw._doc2weight, function(doc, weight){
		kw._doc_weights.push(weight);
	    });
	    kw._doc_weight_sum = kw._doc_weights.reduce(function(acc, v){return acc + v}, 0);

	    kw.on_from_itself = function(){
		kw._fb_from_itself = 1;
	    }

	    kw.off_from_itself = function(){
		kw._fb_from_itself = 0;
	    }

	    kw.on_from_doc = function(doc){
		kw._fb_from_doc += (kw._doc2weight[doc['id']] / kw._doc_weight_sum);
	    }

	    kw.off_from_doc = function(doc){
		kw._fb_from_doc -= (kw._doc2weight[doc['id']] / kw._doc_weight_sum);
	    }

	    kw.get_feedback = function(){
		return Math.abs(self.alpha * kw._fb_from_itself +  (1 - self.alpha) * kw._fb_from_doc); //use abs to avoid the -0.00000000000001 problem
	    }

	    //two-way binding
	    var doc_ids = kw['docs'].map(function(doc){return doc['id']}); //doc ids associated with the keyword
	    kw['docs'] = self.docs.filter(function(doc){return doc_ids.indexOf(doc['id']) >= 0});
	});

	self.docs.forEach(function(doc){
	    //currently,we are only considering doc's feedback coming from keywords associated with it
	    doc._fb_from_itself = 0;
	    doc._fb_from_kw = 0;

	    doc._kw2weight = {};
	    doc['kws'].forEach(function(kw){
		doc._kw2weight[kw['id']] = kw['w'];
	    });

	    doc._kw_weights = [];
	    $.each(doc._kw2weight, function(kw, weight){
		doc._kw_weights.push(weight);
	    });
	    doc._kw_weight_sum = doc._kw_weights.reduce(function(acc, v){return acc + v}, 0);

	    doc.on_from_itself = function(kw){
		//it means feedback from the keyword in itself
		if(kw == undefined){
		    doc._fb_from_itself = 1;
		}
		else{
		    var w = doc._kw2weight[kw['id']] || 0;
		    doc._fb_from_itself += (w / doc._kw_weight_sum);;
		}
	    }

	    doc.off_from_itself = function(kw){
		if(kw == undefined){
		    doc._fb_from_itself = 1;
		}
		else{
		    var w = doc._kw2weight[kw['id']] || 0;
		    doc._fb_from_itself -= (w / doc._kw_weight_sum);;
		}
	    }

	    doc.on_from_kw = function(kw){
		var w = doc._kw2weight[kw['id']] || 0;
		doc._fb_from_kw += (w / doc._kw_weight_sum);
	    }

	    doc.off_from_kw = function(kw){
		var w = doc._kw2weight[kw['id']] || 0;
		doc._fb_from_kw -= (w / doc._kw_weight_sum);
	    }

	    doc.get_feedback = function(){
		//weighted sum
		console.log('get doc feedback: from itself', doc._fb_from_itself , ' from kw ', doc._fb_from_kw);
		return self.beta * doc._fb_from_itself + (1 - self.beta) * doc._fb_from_kw;
	    }

	    var kw_ids = doc['kws'].map(function(kw){return kw['id']});
	    doc['kws'] = self.kws.filter(function(kw){
		return kw_ids.indexOf(kw['id']) >= 0
	    });
	})
    }

    self.define_interaction_rules = function(){
	//feedback directly on docs
	self.docs.forEach(function(doc){
	    doc._is_on = false;
	    doc._is_kw_on_dict = {};

	    doc['is_on'] = function(){
		return doc._is_on;
	    }

	    doc['is_kw_on'] = function(kw){
		if(doc._is_kw_on_dict[kw['id']] == undefined){
		    doc._is_kw_on_dict[kw['id']] = false;
		};
		return  doc._is_kw_on_dict[kw['id']];
	    }

	    doc.get_internal_kw = function(kw_id){
		var kw = doc['kws'].filter(function(kw){
		    return kw['id'] == kw_id;
		})[0];
		if(kw ==  undefined){
		    throw "`kw` is undefined, given kw_id: " + kw_id;
		}
		return kw;
	    }
	    doc['on'] = function(kw){ //doc is active
		if(kw == undefined){
		    console.log('doc', doc['id'], 'becomes ON');
		    doc._is_on = true;

		    doc['kws'].forEach(function(kw){
			//feedback to itself
			doc.on_from_itself(kw);

			doc._is_kw_on_dict[kw['id']] = true;
			//feedback to the keywords associated with it
			kw.on_from_doc(doc);
		    });
		}
		else{
		    console.log('kw ', kw['id'], ' in doc ', doc['id'], 'becomes ON');
		    doc._is_kw_on_dict[kw['id']] = true;

		    //feedback to itself
		    doc.on_from_itself(kw);

		    //feedback to keyword
		    kw.on_from_doc(doc);
		}

		console.log('doc', doc['id'], 'feedback is:', doc.get_feedback())
	    }

	    doc['off'] = function(){ //doc is deactivated
		console.log('doc', doc['id'], 'becomes OFF');
		doc._is_on = false;

		//feedback to itself
		doc.off_from_itself();

		//feedback to the keywords associated with it
		doc['kws'].forEach(function(kw){
		    kw.off(doc)
		});
	    }
	});

	//feedback directly on keywords
	self.kws.forEach(function(kw){
	    kw._is_primary_on = false;
	    kw._is_doc_on_dict = {};
	    kw['is_doc_on'] = function(doc){
		if(kw._is_doc_on_dict[doc['id']] == undefined){
		    kw._is_doc_on_dict[doc['id']] = false;
		}
		return kw._is_doc_on_dict[doc['id']];
	    }
	    kw['is_primary_kw_on'] = function(){
		return kw._is_primary_on;
	    }

	    kw['on'] = function(doc){ //doc is active
		if(doc == undefined){ //clicked from keyword column
		    kw._is_primary_on = true;

		    console.log('kw', kw['id'], 'becomes ON');
		    //feedback to itself
		    kw.on_from_itself();

		    //feedback to the documents associated with it
		    kw['docs'].forEach(function(doc){

			//feedback to doc
			doc.on_from_kw(kw);

			//kw._is_on_dict[doc['id']] = true;
			console.log('doc', doc['id'], 'feedback is:', doc.get_feedback())
		    });
		}
		else{
		    console.log('keyword clicked from document column');
		    kw.on_from_doc(doc);

		    //feedback to doc
		    doc.on_from_kw(kw);
		}
		console.log('kw', kw['id'], 'feedback is:', kw.get_feedback());
	    }

	    kw['off'] = function(doc){ //doc is deactivated
		if(doc == undefined){
		    kw._is_primary_on = false;

		    console.log('kw', kw['id'], 'becomes OFF');
		    //feedback to itself
		    kw.off_from_itself();

		    //feedback to the docs associated with it
		    kw['docs'].forEach(function(doc){
			doc.off_from_kw(kw);
			//kw._is_on_dict[doc['id']] = false;
		    });
		}
		else{
		    console.log('keyword clicked from document column');
		    kw._is_doc_on_dict[doc['id']] = false;
		    //feedback to itself
		    kw.off_from_doc(doc);

		    //feedback to doc
		    doc.off_from_kw(kw);
		}

	    }

	});
    }

    self.resetDisplay = function(){
	self.kw_list_html.reset();
	self.doc_list_html.reset();
    }
    self.display = function(){
	self.resetDisplay();

	//render keywords
	$.each(self.kws, function(idx, kw){
	    if(kw['display']){
		self.kw_list_html.add(kw);
	    }
	    else{
		self.kw_list_html.add(kw, {'classes': 'text-muted'});
	    }
	});

	self.kw_list_html.find('.kw').on('mousewheel', function(event, delta){
	    var step = 0.05
	    var val = $(this).data('feedback_from_itself') || 0;
	    if (delta >= 0){
		if (val + step <= 1){
		    val += step;
		}
		else{
		    val = 1;
		}
	    }
	    else{
		if (val -step >= 0){
		    val -= step;
		}
		else{
		    val = 0;
		}
	    }
	    $(this).find('.feedback').html(val.toFixed(2));
	    $(this).data('feedback', val);
	    event.preventDefault();

	    //keyword feedback to document propagation
	}).filter(function(){ //get only those displayed and bind click to them
	    var kw = $(this).data('get_internal')();
	    return kw['display'];
	}).on('click', function(e){

	    var kw = $(this).data('get_internal')();
	    if(kw.is_primary_kw_on()){
		kw.off();
	    }
	    else{
		kw.on();
	    }

	    //the visual effect stuff
	    kw.update_display();
	    kw['docs'].forEach(function(doc){
		doc.update_display(); //doc changes display
		kw.update_display(doc); //secondary kw changes display
	    });

	    e.stopPropagation();
	});

	//render documents
	$.each(self.docs, function(idx, doc){
	    self.doc_list_html.add(doc);
	});

	//when document is clicked
	self.doc_list_html.find('.doc').on('click', function(){
	    var doc = $(this).data('get_internal')();

	    if(!doc.is_on()){
		doc.on();
	    }
	    else{
		doc.off();
	    }

	    //visual effect stuff
	    doc.update_display();

	    //all kw
	    $.each($(this).find('.kw'), function(idx, obj){
		var _self = $(obj);
		var kw = _self.data('get_internal')();
		kw.update_display(doc);
		kw.update_display();
	    });
	})

	//when keyword under the document is clicked
	self.doc_list_html.find('.kw').on('click', function(e){
	    var doc = $(this).closest('.doc').data('get_internal')();
	    var kw = $(this).data('get_internal')();

	    if(!doc.is_kw_on(kw)){
		kw.on(doc);
	    }
	    else{
		kw.off(doc);
	    }

	    //update the feedback display
	    kw.update_display(doc); //for kw in doc
	    kw.update_display(); //for primary kw

	    doc.update_display();

	    e.stopPropagation();
	});

	self.define_update_rules();
	self.define_interaction_rules();
    }
};

var c = new Content();

$(document).ready(function() {
    if(c.session_id == null){//start a session
	$.post('/api/1.0/recommend', function(res){
	    if(res.errcode === 0){
		$('#responseHtml').html(JSON.stringify(res, undefined, 4));

		c.propagate_from_response(res);
		c.display();
	    }
	})
    }
    else{//continue a new session
    }
});

redpajama_set_name: RedPajamaGithub


text:
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';

const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;

export default class Icon extends Component {
  render () {
    const { className, colorIndex } = this.props;
    let { a11yTitle, size, responsive } = this.props;
    let { intl } = this.context;

    const classes = classnames(
      CLASS_ROOT,
      `${CLASS_ROOT}-microphone`,
      className,
      {
        [`${CLASS_ROOT}--${size}`]: size,
        [`${CLASS_ROOT}--responsive`]: responsive,
        [`${COLOR_INDEX}-${colorIndex}`]: colorIndex
      }
    );

    a11yTitle = a11yTitle || Intl.getMessage(intl, 'microphone');

    const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
    return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000000" strokeWidth="2" d="M8,11 C8,14 9.790861,15 12,15 C14.209139,15 16,14 16,11 L16,5 C16,2 14.209139,1 12,1 C9.790861,1 8,2 8,5 L8,11 Z M4,9 L4,11 C4,16 7.581722,19 12,19 C16.418278,19 20,16 20,11 L20,9 M12,24 L12,19"/></svg>;
  }
};

Icon.contextTypes = {
  intl: PropTypes.object
};

Icon.defaultProps = {
  responsive: true
};

Icon.displayName = 'Microphone';

Icon.icon = true;

Icon.propTypes = {
  a11yTitle: PropTypes.string,
  colorIndex: PropTypes.string,
  size: PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge']),
  responsive: PropTypes.bool
};


text:
using namespace std;

fileWriter::fileWriter()
: _fileName(""),
  _fileStream()
{ }

fileWriter::fileWriter(const string& fileName) :
        _fileName(fileName)
        ,_fileStream(fileName.c_str())
{ }

fileWriter::~fileWriter()
{ }

int fileWriter::open()
{
    try
    {
        _fileStream.open(_fileName.c_str());
    }
    catch (const ios::failure & error)
    {
        cerr << "I/O exception: " << error.what() << endl;
        return EXIT_FAILURE;
    }
    return 0;
}

int fileWriter::open(const string& fileName)
{
    _fileName = fileName;
    return open();
}

int fileWriter::close()
{
    try
    {
        _fileStream.close();
    }
    catch (const ios::failure & error)
    {
        cerr << "I/O exception: " << error.what() << endl;
        return EXIT_FAILURE;
    }
    return 0;
}


text:
package com.jreaper.common.web;

import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.time.ZoneId;

/**
 * Created by roman on 23.02.15.
 */
public interface JDTimeZoneResolver {

    ZoneId resolveTimeZone(HttpServletRequest request) ;

    ZoneId resolveTimeZone(WebRequest request);
}


text:
<?php

namespace Shakyamouni\SiteBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Shakyamouni\SiteBundle\Entity\Slider
 *
 * @ORM\Table(name="slider")
 * @ORM\Entity(repositoryClass="Shakyamouni\SiteBundle\Repository\SliderRepository")
 */
class Slider {

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->isCaption = false;
    }

    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @Gedmo\Timestampable(on="update")
     * @ORM\Column(type="datetime")
     */
    private $updatedAt;

    /**
     * @Gedmo\Slug(fields={"title"})
     * @ORM\Column(length=255, unique=true)
     */
    private $slug;

    /**
     * @var string $title
     * @ORM\Column(name="title", type="string",length=255, nullable=false)
     * @Assert\NotBlank()
     * @Assert\Length(min="1")
     */
    private $title;

    /**
     * @var string $subtitle
     * @ORM\Column(name="subtitle", type="string",length=255, nullable=true)
     * @Assert\Length(min="1")
     */
    private $subtitle;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $picture;

    /**
     * @Assert\File(maxSize="2M")
     */
    public $file;

    /**
     * @var integer $position
     *
     * @ORM\Column(name="position", type="integer")
     */
    private $position;

    /**
     * @ORM\OneToOne(targetEntity="Shakyamouni\SiteBundle\Entity\Event", cascade={"persist"})
     * @ORM\JoinColumn(name="event_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
     */
    private $event;

    /**
     * @ORM\OneToOne(targetEntity="Shakyamouni\SiteBundle\Entity\Article", cascade={"persist"})
     * @ORM\JoinColumn(name="article_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
     */
    private $article;

    /**
     * @ORM\OneToOne(targetEntity="Shakyamouni\MenuBundle\Entity\SubCategory", cascade={"persist"})
     * @ORM\JoinColumn(name="subcategory_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
     */
    private $subcategory;

    /**
     * @ORM\OneToOne(targetEntity="Shakyamouni\SiteBundle\Entity\ArticleEvent", cascade={"persist"})
     * @ORM\JoinColumn(name="articleevent_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
     */
    private $articleevent;

    /**
     * @var boolean
     *
     * @ORM\Column(name="is_caption", type="boolean", nullable=true)
     */
    private $isCaption;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

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

    /**
     * Set subtitle
     *
     * @param string $subtitle
     */
    public function setSubtitle($subtitle)
    {
        $this->subtitle = $subtitle;
    }

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

    /**
     * Set picture
     *
     * @param string $picture
     */
    public function setPicture($picture)
    {
        $this->picture = $picture;
    }

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

    /**
     * Set position
     *
     * @param integer $position
     */
    public function setPosition($position)
    {
        $this->position = $position;
    }

    /**
     * Get position
     *
     * @return integer
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Set createdAt
     *
     * @param datetime $createdAt
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * Get createdAt
     *
     * @return datetime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param datetime $updatedAt
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;
    }

    /**
     * Get updatedAt
     *
     * @return datetime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set event
     *
     * @param \Shakyamouni\SiteBundle\Entity\Event $event
     * @return Slider
     */
    public function setEvent(\Shakyamouni\SiteBundle\Entity\Event $event = null)
    {
        $this->event = $event;

        return $this;
    }

    /**
     * Get event
     *
     * @return \Shakyamouni\SiteBundle\Entity\Event
     */
    public function getEvent()
    {
        return $this->event;
    }

    /**
     * Set article
     *
     * @param \Shakyamouni\SiteBundle\Entity\Article $article
     * @return Slider
     */
    public function setArticle(\Shakyamouni\SiteBundle\Entity\Article $article = null)
    {
        $this->article = $article;

        return $this;
    }

    /**
     * Get article
     *
     * @return \Shakyamouni\SiteBundle\Entity\Article
     */
    public function getArticle()
    {
        return $this->article;
    }

    /**
     * Set slug
     *
     * @param string $slug
     * @return Slider
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

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

    public function getWebPath()
    {
        return null === $this->picture ? null : $this->getUploadDir() . '/' . $this->picture;
    }

    protected function getUploadRootDir()
    {
        // le chemin absolu du répertoire dans lequel sauvegarder les photos de profil
        return __DIR__ . '/../../../../web/' . $this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
        return 'uploads/carrousel';
    }

    public function uploadProfilePicture()
    {
        // Nous utilisons le nom de fichier original, donc il est dans la pratique
        // nécessaire de le nettoyer pour éviter les problèmes de sécurité
        // move copie le fichier présent chez le client dans le répertoire indiqué.
        $securedFileName = sha1(uniqid(mt_rand(), true). $this->file->getClientOriginalName() * microtime(false)).'.'.$this->file->guessExtension();

        $this->file->move($this->getUploadRootDir(), $securedFileName);

        // On sauvegarde le nom de fichier
        $this->picture = $securedFileName;

        // La propriété file ne servira plus
        $this->file = null;
    }

    /**
     * Set isCaption
     *
     * @param boolean $isCaption
     * @return Slider
     */
    public function setIsCaption($isCaption)
    {
        $this->isCaption = $isCaption;

        return $this;
    }

    /**
     * Get isCaption
     *
     * @return boolean
     */
    public function getIsCaption()
    {
        return $this->isCaption;
    }

    /**
     * Set articleevent
     *
     * @param \Shakyamouni\SiteBundle\Entity\ArticleEvent $articleevent
     * @return Slider
     */
    public function setArticleevent(\Shakyamouni\SiteBundle\Entity\ArticleEvent $articleevent = null)
    {
        $this->articleevent = $articleevent;

        return $this;
    }

    /**
     * Get articleevent
     *
     * @return \Shakyamouni\SiteBundle\Entity\ArticleEvent
     */
    public function getArticleevent()
    {
        return $this->articleevent;
    }

    /**
     * Set subcategory
     *
     * @param \Shakyamouni\MenuBundle\Entity\SubCategory $subcategory
     * @return Slider
     */
    public function setSubcategory(\Shakyamouni\MenuBundle\Entity\SubCategory $subcategory = null)
    {
        $this->subcategory = $subcategory;

        return $this;
    }

    /**
     * Get subcategory
     *
     * @return \Shakyamouni\MenuBundle\Entity\SubCategory
     */
    public function getSubcategory()
    {
        return $this->subcategory;
    }
}


text:
//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE

package tripleplay.util;

import java.util.HashMap;
import java.util.Map;

import playn.core.Platform;

/**
 * Provides logging services that are routed to the appropriate logging destination on the client
 * or server. A useful usage pattern is for a library or game to define a shared {@code Log} class
 * like so:
 *
 * <pre>{@code
 * import tripleplay.util.Logger;
 * public class Log {
 *   public static final Logger log = new Logger("libident");
 * }
 * }</pre>
 *
 * and then import {@code Log.log} statically into classes so that they can invoke {@code
 * log.info}, etc.
 */
public class Logger
{
    /** Tags a log message with a particular severity level. */
    public enum Level { DEBUG, INFO, WARNING, ERROR, OFF; }

    /**
     * Wires the logging front-end to the logging back-end. See {@link #setImpl}.
     */
    public interface Impl {
        /** Logs the supplied message at the supplied level. */
        void log (Level level, String ident, String message, Throwable t);
    }

    /** Manages the target log levels for a given ident. */
    public static class Levels {
        /** Configures the default log level. Messages with severity lower than this level will not
         * be logged unless a specific level is set for their identifier. */
        public Levels setDefault (Level level) {
            _defaultLevel = level;
            return this;
        }

        /** Configures the log level for messages with the supplied identifier. Messages with the
         * supplied identifier with severity lower than this level will not be logged regardless of
         * the default log level. Pass null to clear any level cutoff for {@code ident}. */
        public Levels set (String ident, Level level) {
            _levels.put(ident, level);
            return this;
        }

        /** Configures the log level for messages from the supplied logger. Messages from the
         * supplied logger with severity lower than this level will not be logged regardless of
         * the default log level. Pass null to clear any level cutoff for {@code logger}. */
        public Levels set (Logger logger, Level level) {
            _levels.put(logger._ident, level);
            return this;
        }

        /** Returns the current default log level. */
        public Level defaultLevel () {
            return _defaultLevel;
        }

        /** Returns the current log level for the specified identifier, or null if no level is
         * configured for that identifier. */
        public Level level (String ident) {
            return _levels.get(ident);
        }

        /** Returns true if a message with the specified level and ident should be logged. */
        public boolean shouldLog (Level level, String ident) {
            Level ilevel = _levels.get(ident);
            if (ilevel != null) return level.ordinal() >= ilevel.ordinal();
            return level.ordinal() >= _defaultLevel.ordinal();
        }

        protected Level _defaultLevel = Level.DEBUG;
        protected Map<String,Level> _levels = new HashMap<String,Level>();
    }

    /**
     * A logging back-end that writes to PlayN.
     */
    public static class PlayNImpl implements Impl {
        private final Platform plat;
        public PlayNImpl (Platform plat) {
            this.plat = plat;
        }
        public void log (Level level, String ident, String message, Throwable t) {
            String msg = ident + ": " + message;
            switch (level) {
            case DEBUG:
                if (t != null) plat.log().debug(msg, t);
                else plat.log().debug(msg);
                break;
            default:
            case INFO:
                if (t != null) plat.log().info(msg, t);
                else plat.log().info(msg);
                break;
            case WARNING:
                if (t != null) plat.log().warn(msg, t);
                else plat.log().warn(msg);
                break;
            case ERROR:
                if (t != null) plat.log().error(msg, t);
                else plat.log().error(msg);
                break;
            }
        }
    }

    /** Log levels can be configured via this instance. */
    public static Levels levels = new Levels();

    /**
     * Configures the logging back-end. This should be called before any code that makes use of the
     * logging services. The default back-end logs to {@code stderr}, which is useful when running
     * in unit tests. {@code null} may be supplied to restore the default (stderr) back-end.
     */
    public static void setImpl (Impl impl) {
        _impl = (impl == null) ? DEFAULT : impl;
    }

    /**
     * Formats and returns the supplied message and key/value arguments as
     * {@code message [key=value, key=value, ...]}.
     */
    public static String format (Object message, Object... args) {
        return format(new StringBuilder().append(message).append(" ["), args).append("]").toString();
    }

    /**
     * Formats the supplied key/value arguments into the supplied string builder as {@code
     * key=value, key=value, ...}.
     * @return the supplied string builder.
     */
    public static StringBuilder format (StringBuilder into, Object... args) {
        for (int ii = 0, ll = args.length/2; ii < ll; ii++) {
            if (ii > 0) {
                into.append(", ");
            }
            into.append(args[2*ii]).append("=").append(args[2*ii+1]);
        }
        return into;
    }

    /**
     * Creates a logger with the specified ident string.
     */
    public Logger (String ident) {
        _ident = ident;
    }

    /**
     * Tests if this logger will output messages of the given level.
     */
    public boolean shouldLog (Level level) {
        return levels.shouldLog(level, _ident);
    }

    /**
     * Logs a debug message.
     *
     * @param message the text of the message.
     * @param args a series of zero or more key/value pairs followed by an optional {@link
     * Throwable} cause.
     */
    public void debug (String message, Object... args) {
        if (levels.shouldLog(Level.DEBUG, _ident)) {
            log(Level.DEBUG, _ident, message, args);
        }
    }

    /**
     * Logs an info message.
     *
     * @param message the text of the message.
     * @param args a series of zero or more key/value pairs followed by an optional {@link
     * Throwable} cause.
     */
    public void info (String message, Object... args) {
        if (levels.shouldLog(Level.INFO, _ident)) {
            log(Level.INFO, _ident, message, args);
        }
    }

    /**
     * Logs a warning message.
     *
     * @param message the text of the message.
     * @param args a series of zero or more key/value pairs followed by an optional {@link
     * Throwable} cause.
     */
    public void warning (String message, Object... args) {
        if (levels.shouldLog(Level.WARNING, _ident)) {
            log(Level.WARNING, _ident, message, args);
        }
    }

    /**
     * Logs an error message.
     *
     * @param message the text of the message.
     * @param args a series of zero or more key/value pairs followed by an optional {@link
     * Throwable} cause.
     */
    public void error (String message, Object... args) {
        if (levels.shouldLog(Level.ERROR, _ident)) {
            log(Level.ERROR, _ident, message, args);
        }
    }

    protected final String _ident;

    protected void log (Level level, String ident, String message, Object... args) {
        StringBuilder sb = new StringBuilder().append(message);
        if (args.length > 1) {
            sb.append(" [");
            format(sb, args);
            sb.append("]");
        }
        Object error = (args.length % 2 == 1) ? args[args.length-1] : null;
        _impl.log(level, ident, sb.toString(), (Throwable)error);
    }

    protected static final Impl DEFAULT = new Impl() {
        @Override public void log (Level level, String ident, String message, Throwable t) {
            System.out.println(ident + ": " + message);
            if (t != null) {
                t.printStackTrace(System.out);
            }
        }
    };

    protected static Impl _impl = DEFAULT;
}


text:
import {Component,Input} from 'angular2/core';
import {WeatherItem} from './weather-item';
@Component({
    selector: 'weather-item',
    template: `

{{ weatherItem.cityName }}

{{ weatherItem.description }}

            {{ weatherItem.temperature }}°C

                `,
    styleUrls:['src/css/weather-item.css'],
    // inputs:['weatherItem : item']
})
export class WeatherItemComponent{
    @Input('item') weatherItem : WeatherItem;

}


text:
package com;

import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import com.model.*;
import com.core.BasetableFactory;
import com.jspsmart.upload.Request;

public class BasetableFactoryProxy extends BasetableFactory {
    private BasetableFactory factory;
    public BasetableFactoryProxy(BasetableFactory factory) {
        this.factory = factory;
    }

    public int getRow(String sql) {
        return factory.getRow(sql);
    }

    public boolean CreateUser(HttpServletRequest request) {
         System.out.print("BasetableFactoryProxy.javaÖÐ:"+request+"½áÊø");
        return factory.CreateUser(request);
    }

    public User SearchUser(String sql) {
        return factory.SearchUser(sql);
    }

    public Collection ListHead(int page, String sql) {
        return factory.ListHead(page, sql);
    }

    public Collection ListUser(int page, String sql) {
        return factory.ListUser(page, sql);
    }

    public Head SearchHead(String sql) {
        return factory.SearchHead(sql);
    }

    public boolean CreateHead(String iid, String name,int state) {
        return factory.CreateHead(iid, name, state);
    }

    public Collection ListAffiche(int page, String sql) {
        return factory.ListAffiche(page, sql);
    }

    public Affiche SearchAffiche(String sql) {
        return factory.SearchAffiche(sql);
    }

    public boolean CreateAffiche(HttpServletRequest request) {
        return factory.CreateAffiche(request);
    }

    public boolean DeleteAffiche(String sql) {
        return factory.DeleteAffiche(sql);
    }

    public Collection ListNew(int page, String sql) {
        return factory.ListNew(page, sql);
    }

    public New SearchNew(String sql) {
        return factory.SearchNew(sql);
    }

    public boolean CreateNew(HttpServletRequest request) {
        return factory.CreateNew(request);
    }

    public boolean DeleteNew(String sql) {
        return factory.DeleteNew(sql);
    }

    public Collection ListLink(int page, String sql) {
        return factory.ListLink(page, sql);
    }

    public Link SearchLink(String sql) {
        return factory.SearchLink(sql);
    }

    public boolean CreateLink(HttpServletRequest request) {
        return factory.CreateLink(request);
    }

    public boolean DeleteLink(String sql) {
        return factory.DeleteLink(sql);
    }

    public Collection ListSsort(int page, String sql) {
        return factory.ListSsort(page, sql);
    }

    public Collection ListSsort(String sql) {
        return factory.ListSsort(sql);
    }

    public Ssort SearchSsort(String sql) {
        return factory.SearchSsort(sql);
    }

    public boolean CreateSsort(HttpServletRequest request) {
        return factory.CreateSsort(request);
    }

    public boolean DeleteSsort(String sql) {
        return factory.DeleteSsort(sql);
    }

    public Collection ListSoft(int page, String sql) {
        return factory.ListSoft(page,sql);
    }

    public Soft SearchSoft(String sql) {
        return factory.SearchSoft(sql);
    }

    public boolean CreateSoft(Request request,String path) {
        return factory.CreateSoft(request,path);
    }

    public boolean DeleteSoft(HttpServletRequest request,String sql) {
        return factory.DeleteSoft(request,sql);
    }

    public Collection ListResolvent(String sql) {
        return factory.ListResolvent(sql);
    }

    public Resolvent SearchResolvent(String sql) {
        return factory.SearchResolvent(sql);
    }

    public boolean CreateResolvent(Request request,String iid) {
        return factory.CreateResolvent(request,iid);
    }

    public boolean DeleteResolvent(String sql) {
        return factory.DeleteResolvent(sql);
    }

    public Collection ListSoft(String sql) {
        return factory.ListSoft(sql);
    }

    public Collection ListResolvent(int page, String sql) {
        return factory.ListResolvent(page,sql);
    }

    public Collection ListQuestion(int page, String sql) {
        return factory.ListQuestion(page,sql);
    }

    public Question SearchQuestion(String sql) {
        return factory.SearchQuestion(sql);
    }

    public boolean CreateQuestion(HttpServletRequest request) {
        return factory.CreateQuestion(request);
    }

    public boolean DeleteQuestion(String sql) {
        return factory.DeleteQuestion(sql);
    }

    public Collection ListNew(String sql) {
        return factory.ListNew(sql);
    }

    public Collection ListQuestion(String sql) {
        return factory.ListQuestion(sql);
    }

    public Collection ListGuestboard(int page, String sql) {
        return factory.ListGuestboard(page,sql);
    }

    public Collection ListGuestboard(String sql) {
        return factory.ListGuestboard(sql);
    }

    public Guestboard SearchGuestboard(String sql) {
        return factory.SearchGuestboard(sql);
    }

    public boolean CreateGuestboard(HttpServletRequest request) {
        return factory.CreateGuestboard(request);
    }

    public boolean DeleteGuestboard(String sql) {
        return factory.DeleteGuestboard(sql);
    }

    public Collection ListMend(int page, String sql) {
        return factory.ListMend(page,sql);
    }

    public Collection ListMend(String sql) {
        return factory.ListMend(sql);
    }

    public Mend SearchMend(String sql) {
        return factory.SearchMend(sql);
    }

    public boolean CreateMend(Request request,String path) {
        return factory.CreateMend(request,path);
    }

    public boolean DeleteMend(HttpServletRequest request,String sql) {
        return factory.DeleteMend(request,sql);
    }

    public boolean DeleteHead(HttpServletRequest request, String sql) {
        return factory.DeleteHead(request,sql);
    }

//    public Collection ListFsort(int page, String sql) {
//        return factory.ListFsort(page,sql);
//    }
//
//    public Collection ListFsort(String sql) {
//        return factory.ListFsort(sql);
//    }
//
//    public Fsort SearchFsort(String sql) {
//        return factory.SearchFsort(sql);
//    }
//
//    public boolean CreateFsort(HttpServletRequest request) {
//        return factory.CreateFsort(request);
//    }
//
//    public boolean DeleteFsort(String sql) {
//        return factory.DeleteFsort(sql);
//    }

    public Collection ListAffiche(String sql) {
        return factory.ListAffiche(sql);
    }
}


text:
require 'mechanize'

doi_numbers = []
repeat = true
agent = Mechanize.new
page = agent.get("http://onlinelibrary.wiley.com/doi/10.1111/jacf.1988.1.issue-1/issuetoc")
while repeat == true
   page.search(".citation").search("p").each do |p|
      if p.text.include? "DOI:"
        arr = p.text.split('|')
        doi_numbers << arr.last
      end
    end
    if next_link = page.link_with(css: 'a.next')
    page = next_link.click
else
    repeat = false
    end
end
x = 1

doi_numbers.each do |doi|

  agent = Mechanize.new
  page = agent.get("http://sci-hub.cc/#{doi.split(' ').last}")
  link = page.search("#save").search('a').attribute('onclick').value.gsub('location.href=\'','')
  link = link.gsub('?download=true\'','')
  agent.pluggable_parser.default = Mechanize::Download
  agent.get(link).save(File.join("./pdfs/", "#{x}.pdf"))
  puts "#{doi}.pdf saved"
  x += 1
  sleep 600

end


text:
package com.streamsets.datacollector.runner.production;

import com.streamsets.datacollector.execution.runner.common.RulesConfigLoader;
import com.streamsets.datacollector.execution.runner.common.ThreadHealthReporter;
import com.streamsets.datacollector.runner.Observer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RulesConfigLoaderRunnable implements Runnable {

  public static final int SCHEDULED_DELAY = 2;
  public static final String RUNNABLE_NAME = "RulesConfigLoaderRunnable";
  private static final Logger LOG = LoggerFactory.getLogger(RulesConfigLoaderRunnable.class);

  private final RulesConfigLoader rulesConfigLoader;
  private final Observer observer;
  private final ThreadHealthReporter threadHealthReporter;

  public RulesConfigLoaderRunnable(ThreadHealthReporter threadHealthReporter, RulesConfigLoader rulesConfigLoader,
                                   Observer observer) {
    this.rulesConfigLoader = rulesConfigLoader;
    this.observer = observer;
    this.threadHealthReporter = threadHealthReporter;
  }

  @Override
  public void run() {
    String originalName = Thread.currentThread().getName();
    Thread.currentThread().setName(originalName + "-" + RUNNABLE_NAME);
    try {
      threadHealthReporter.reportHealth(RUNNABLE_NAME, SCHEDULED_DELAY, System.currentTimeMillis());
      rulesConfigLoader.load(observer);
    } catch (Exception e) {
      LOG.error("Stopping the Rules Config Loader, Reason: {}", e.toString(), e);
      return;
    } finally {
      Thread.currentThread().setName(originalName);
    }
  }
}


text:
namespace lslboost
{
    template< class T >
    struct range_value : iterator_value< typename range_iterator<T>::type >
    { };
}

#endif


text:
author: rctay
categories:
  - Events
  - Friday Hacks
comments: true
date: 2011-10-28T00:00:00.000Z
title: 'Friday Hacks #7'
url: /2011/10/friday-hacks-7
---

Notice: the NUS Hackers site continues to be black for this week. Last week, just as we were about to change it back, we received news of another passing - John McCarthy.

Time: 7.30-10.00

Location: University Town, ERC, Seminar Room 3

Agenda:

In memory of John McCarthy, father of Lisp and AI pioneer, we'll be having a short introduction to Scheme, a dialect of Lisp. Anyone who's well-versed with Lisp stuff (Common Lisp, Clojure, S-expressions, continuations) are welcome to share.


text:
package org.apache.logging.log4j.core.selector;

import org.apache.logging.log4j.core.async.AsyncLoggerContextSelector;
import org.apache.logging.log4j.core.async.BasicAsyncLoggerContextSelector;

public class CoreContextSelectors {

    public static final Class<?>[] CLASSES = new Class<?>[] {
            ClassLoaderContextSelector.class,
            BasicContextSelector.class,
            AsyncLoggerContextSelector.class,
            BasicAsyncLoggerContextSelector.class
    };

}


text:
require File.expand_path('../support/helpers', __FILE__)

describe 'apache2::mod_include' do
  include Helpers::Apache

  it 'enables include_module' do
    apache_enabled_modules.must_include 'include_module'
  end

  it 'drops off the include module configuration' do
    assert_match(/AddType text\/html .shtml/, File.read("#{node['apache']['dir']}/mods-enabled/include.conf"))
    assert_match(/AddOutputFilter INCLUDES .shtml/, File.read("#{node['apache']['dir']}/mods-enabled/include.conf"))
  end
end


text:
/*jslint browser: true*/
/*global BGo:false, BGoGame: false, BGoViewModel:false, BGoSvgBoardView:false, BGoBasicCapturesView:false, BGoBasicCommandsView:false, describe, it, expect, spyOn */

/*
var g1 = null;
var vm1 = null;
var v1 = null;
var v2 = null;
var v3 = null;
var commandsView = null;
var playMove = function (x, y) { "use strict"; g1.viewModel.userClick(x, y); };
*/

define(['BGo'], function(BGo) {

    describe('BGo', function () {
        "use strict";

        describe('.isElement', function () {

            it('returns false if object is null', function() {

                // Arrange
                var inputValue = null;
                var expectedResult = false;

                // Action
                var actualResult = BGo.isElement(inputValue)

                // Assert
                expect(actualResult).toBe(expectedResult);

            });

            it('returns false if object is undefined', function() {

                // Arrange
                var inputValue = undefined;
                var expectedResult = false;

                // Action
                var actualResult = BGo.isElement(inputValue)

                // Assert
                expect(actualResult).toBe(expectedResult);

            });

            it('returns false if object is Object', function() {

                // Arrange
                var inputValue = new Object();
                var expectedResult = false;

                // Action
                var actualResult = BGo.isElement(inputValue)

                // Assert
                expect(actualResult).toBe(expectedResult);

            });

            it('returns true if object is HTMLElement', function() {

                // Arrange
                var inputValue = document.createElement('div');
                var expectedResult = true;

                // Action
                var actualResult = BGo.isElement(inputValue)

                // Assert
                expect(actualResult).toBe(expectedResult);

            });

        });

        describe('.getObjectTypeName', function() {

            it ('returns null if passed null', function() {

                // Arrange
                var inputValue = null;
                var expectedResult = null;

                // Action
                var actualResult = BGo.getObjectTypeName(inputValue);

                // Assert
                expect(actualResult).toBe(expectedResult);

            });

            it ('returns null if passed undefined', function() {

                // Arrange
                var inputValue = undefined;
                var expectedResult = null;

                // Action
                var actualResult = BGo.getObjectTypeName(inputValue);

                // Assert
                expect(actualResult).toBe(expectedResult);

            });

            it ('returns "Object" if passed an Object', function() {

                // Arrange
                var inputValue = new Object();
                var expectedResult = 'Object';

                // Action
                var actualResult = BGo.getObjectTypeName(inputValue);

                // Assert
                expect(actualResult).toBe(expectedResult);
            });

            it ('returns "Function" if passed a function', function() {

                // Arrange
                var inputValue = function blah() { };
                var expectedResult = 'Function';

                // Action
                var actualResult = BGo.getObjectTypeName(inputValue);

                // Assert
                expect(actualResult).toBe(expectedResult);
            });

            it ('returns "MyClass" if passed a instance of a prototype', function() {

                // Arrange
                var myClass = function MyClass() { };
                var inputValue = new myClass();
                var expectedResult = 'MyClass';

                // Action
                var actualResult = BGo.getObjectTypeName(inputValue);

                // Assert
                expect(actualResult).toBe(expectedResult);
            });

            it ('throws "Objects must be declared..." exception when object prototype not set up correctly.', function() {

                // Arrange
                var myClass = function () { };
                var inputValue = new myClass();
                var expectedResult = 'MyClass';

                // Action
                var action = function() { var actualResult = BGo.getObjectTypeName(inputValue); }

                // Assert
                expect(action).toThrow('Objects must be declared using "function <FunctionName>()" syntax not "var <FunctionName> = function() {}" syntax.');

            });

        });

        describe('.getIndexOf', function() {

            it('throw "board index out of range" if x is equal to the board size', function() {

                // Arrange
                var x = 9;
                var y = 0;
                var boardSize = 9;
                var expectedResult = 0;

                // Action
                var action = function() { BGo.getIndexOf(x, y, boardSize); }

                // Assert
                expect(action).toThrow('Board index out of range');

            });

            it('throw "board index out of range" if x is over the board size', function() {

                // Arrange
                var x = 100;
                var y = 0;
                var boardSize = 9;
                var expectedResult = 0;

                // Action
                var action = function() { BGo.getIndexOf(x, y, boardSize); }

                // Assert
                expect(action).toThrow('Board index out of range');

            });

            it('throw "board index out of range" if x less than 0', function() {

                // Arrange
                var x = -1;
                var y = 0;
                var boardSize = 9;
                var expectedResult = 0;

                // Action
                var action = function() { BGo.getIndexOf(x, y, boardSize); }

                // Assert
                expect(action).toThrow('Board index out of range');

            });

            it('throw "board index out of range" if y is equal to the board size', function() {

                // Arrange
                var x = 0;
                var y = 9;
                var boardSize = 9;
                var expectedResult = 0;

                // Action
                var action = function() { BGo.getIndexOf(x, y, boardSize); }

                // Assert
                expect(action).toThrow('Board index out of range');

            });

            it('throw "board index out of range" if y is over the board size', function() {

                // Arrange
                var x = 0;
                var y = -1;
                var boardSize = 9;
                var expectedResult = 0;

                // Action
                var action = function() { BGo.getIndexOf(x, y, boardSize); }

                // Assert
                expect(action).toThrow('Board index out of range');

            });

            it('throw "board index out of range" if y less than 0', function() {

                // Arrange
                var x = 0;
                var y = -1;
                var boardSize = 9;
                var expectedResult = 0;

                // Action
                var action = function() { BGo.getIndexOf(x, y, boardSize); }

                // Assert
                expect(action).toThrow('Board index out of range');

            });

            it('returns the correct index the top left of a 9x9', function() {

                // Arrange
                var x = 0;
                var y = 0;
                var boardSize = 9;
                var expectedResult = 0;

                // Action
                var actualResult = BGo.getIndexOf(x, y, boardSize);

                // Assert
                expect(actualResult).toBe(expectedResult);

            })

            it('returns the correct index the top right of a 9x9', function() {

                // Arrange
                var x = 8;
                var y = 0;
                var boardSize = 9;
                var expectedResult = 8;

                // Action
                var actualResult = BGo.getIndexOf(x, y, boardSize);

                // Assert
                expect(actualResult).toBe(expectedResult);

            })

            it('returns the correct index the bottom left of a 9x9', function() {

                // Arrange
                var x = 0;
                var y = 8;
                var boardSize = 9;
                var expectedResult = 72;

                // Action
                var actualResult = BGo.getIndexOf(x, y, boardSize);

                // Assert
                expect(actualResult).toBe(expectedResult);

            })

            it('returns the correct index the bottom right of a 9x9', function() {

                // Arrange
                var x = 8;
                var y = 8;
                var boardSize = 9;
                var expectedResult = 80;

                // Action
                var actualResult = BGo.getIndexOf(x, y, boardSize);

                // Assert
                expect(actualResult).toBe(expectedResult);

            })

            it('returns the correct index the top left of a 19x19', function() {

                // Arrange
                var x = 0;
                var y = 0;
                var boardSize = 19;
                var expectedResult = 0;

                // Action
                var actualResult = BGo.getIndexOf(x, y, boardSize);

                // Assert
                expect(actualResult).toBe(expectedResult);

            })

            it('returns the correct index the top right of a 19x19', function() {

                // Arrange
                var x = 18;
                var y = 0;
                var boardSize = 19;
                var expectedResult = 18;

                // Action
                var actualResult = BGo.getIndexOf(x, y, boardSize);

                // Assert
                expect(actualResult).toBe(expectedResult);

            })

            it('returns the correct index the bottom left of a 19x19', function() {

                // Arrange
                var x = 0;
                var y = 18;
                var boardSize = 19;
                var expectedResult = 342;

                // Action
                var actualResult = BGo.getIndexOf(x, y, boardSize);

                // Assert
                expect(actualResult).toBe(expectedResult);

            })

            it('returns the correct index the bottom right of a 19x19', function() {

                // Arrange
                var x = 18;
                var y = 18;
                var boardSize = 19;
                var expectedResult = 360;

                // Action
                var actualResult = BGo.getIndexOf(x, y, boardSize);

                // Assert
                expect(actualResult).toBe(expectedResult);

            })

        });

    });

});


text:
__metaclass__ = type

from netaddr import IPNetwork

def network_address(net_addr):
    """ Converts a CIDR network address/mask string to a network address.

    Args:
        net_addr (str): a network address/mask string in
            the format A.B.C.D/E.

    Returns:
        str: The network address specified by the input net_addr.
    """
    ip = IPNetwork(net_addr)
    return(str(ip.network))

class FilterModule(object):

    def filters(self):
        return {
            'network_address': network_address,
        }


text:
class Milestone < ActiveRecord::Base
  belongs_to :company
  belongs_to :project
  belongs_to :user

  has_many :tasks, :dependent => :nullify

  def percent_complete
    p = 0.0

    complete = self.completed_tasks * 1.0
    total =  self.total_tasks * 1.0
    return 0.0 if total == 0
    p = (complete / total) * 100.0
  end

  def complete?
    (self.completed_tasks == self.total_tasks) || (!self.completed_at.nil?)
  end

  def to_tip(options = { })
    res = "
"
    res << "
#{_('Name')}	 #{self.name}
"
    res << "
#{_('Due Date')}	 #{options[:user].tz.utc_to_local(due_at).strftime_localized("%A, %d %B %Y")}
" unless self.due_at.nil?
    res << "
#{_('Owner')}	 #{self.user.name}
" unless self.user.nil?
    res << "
#{_('Progress')}	 #{self.completed_tasks.to_i} / #{self.total_tasks.to_i} #{_('Complete')}
"
    res << "
#{_('Description')}	#{self.description.gsub(/\n/, '
').gsub(/\"/,'"')}
" if( self.description && self.description.strip.length > 0)
    res << "
"
    res.gsub(/\"/,'"')
  end

  def due_date
    unless @due_date
      if due_at.nil?
        last = self.tasks.collect{ |t| t.due_at.to_time.to_f if t.due_at }.compact.sort.last
        @due_date = Time.at(last).to_datetime if last
      else
        @due_date = due_at
      end
    end
    @due_date
  end

  def scheduled_date
    (self.scheduled? ? self.scheduled_at : self.due_at)
  end

  def worked_minutes
    if @minutes.nil?
      @minutes = WorkLog.sum('work_logs.duration', :joins => "INNER JOIN tasks ON tasks.milestone_id = #{self.id}", :conditions => ["work_logs.task_id = tasks.id AND tasks.completed_at IS NULL"] ) || 0
      @minutes /= 60
    end
    @minutes
  end

  def duration
    if @duration.nil?
      @duration = Task.sum(:duration, :conditions => ["tasks.milestone_id = ? AND tasks.completed_at IS NULL AND tasks.scheduled = 0", self.id]) || 0
      @duration += Task.sum(:scheduled_duration, :conditions => ["tasks.milestone_id = ? AND tasks.completed_at IS NULL AND tasks.scheduled = 1", self.id]) || 0
    end
    @duration
  end

end


text:
goog.provide('DD.fx.DragDropHelper');

goog.require('DD.fx.CustomDragDrop');
goog.require('DD.fx.DragScroll');
goog.require('DD.fx.DragSource');
goog.require('DD.fx.DropTarget');
goog.require('DD.fx.ShuffleGrid');
goog.require('DD.fx.HammerWrapper');

/**
 * Вспомогательная сборка DragDrop инструментария
 * @param {Object=} [settings] Список входящих параметров
 * @param {String} [settings.allowClassNames] Название класса, учавствующий в DragDrop
 * @param {Number} [settings.gridGutter] Отступ (margin) у элементов сетки, если отступ создан при помощи padding, gridGutter передавать не нужно
 * @param {Array} [settings.source] Массив, соддержащий ссылки на DOM-элементы. Являются контейнерами, у которых может начинаться событие onGetDragSource
 * @param {Array} [settings.target] Массив, соддержащий ссылки на DOM-элементы. Являются контейнерами, у которых может начинаться событие onGetDropTarget
 * @param {Array} [settings.scroll] Массив, соддержащий ссылки на DOM-элементы. Являются контейнерами, которые имеют полосу скроллирования
 * @param {Array} [settings.pixelThreshold] Пиксельный порог захвата элемента
 * @param {Array} [settings.lapseThreshold] Временной порог захвата элемента
 * @param {Array} [settings.grid] Массив, соддержащий ссылки на DOM-элементы. Являются контейнерами, у которых будут создаваться виртуальная сетка элементов
 * @extends goog.events.EventTarget
 * @author Антон Пархоменко valianton@mail.ru
 * @this DD.fx.DragDropHelper
 * @version 1.0.2
 * @constructor
 */
DD.fx.DragDropHelper = function(settings)
{
	settings = settings || {};

	this.allowClassNames_       = 'allowClassNames' in settings ? settings.allowClassNames : '';
	this.showScrollArea_        = 'showScrollArea'  in settings ? settings.showScrollArea  : false;

	this.gridGutter_            = settings.gridGutter;
	this.dropZoneTime_          = settings.dropZoneTime;
	this.pixelThreshold_        = settings.pixelThreshold;
	this.lapseThreshold_        = settings.lapseThreshold;
	this.scrollParentMode_      = settings.scrollParentMode;
	this.scrollParent_          = settings.scrollParent;
	this.smoothScroll_          = settings.smoothScroll;
	this.ignored_               = settings.ignoreClassNames;
	this.imageAlign_            = settings.imageAlign;
	this.showDefaultImageTime_  = settings.showDefaultImageTime;
	this.showDragImage_         = settings.showDragImage;
	this.debugMode_             = settings.debugMode;
	this.dragObjectContainer_   = settings.dragObjectContainer;

	this.source_ = 'source' in settings ? settings.source : [];
	(this.source_.length > 0) && this.initDragSource_(this.source_);

	this.target_ = 'target' in settings ? settings.target : [];
	(this.target_.length > 0) && this.initDropTarget_(this.target_);

	this.scroll_ = 'scroll' in settings ? settings.scroll : [];
	(this.scroll_.length > 0) && this.initDragScroll_(this.scroll_);

	this.grid_ 	= 'grid' in settings ? settings.grid : [];
	(this.grid_.length > 0) && this.initShuffleGrid_(this.grid_);

	this.installEventDependence_();

	this.onCreateImage    = goog.isFunction(settings.onCreateImage)     ? settings.onCreateImage    : null;
	this.onGetDragSource  = goog.isFunction(settings.onGetDragSource)   ? settings.onGetDragSource  : null;
	this.onDragStart      = goog.isFunction(settings.onDragStart)       ? settings.onDragStart      : null;
	this.onDragEnd        = goog.isFunction(settings.onDragEnd)         ? settings.onDragEnd        : null;
	this.onDragOverScroll = goog.isFunction(settings.onDragOverScroll)  ? settings.onDragOverScroll : null;
	this.onDragDrop       = goog.isFunction(settings.onDragDrop)        ? settings.onDragDrop       : null;
	this.onGetDropTarget  = goog.isFunction(settings.onGetDropTarget)   ? settings.onGetDropTarget  : null;
	this.onDragOver       = goog.isFunction(settings.onDragOver)        ? settings.onDragOver       : null;

	this.enterDocument();
};
goog.inherits(DD.fx.DragDropHelper, DD.fx.CustomDragDrop);

goog.scope(function()
{
	/** @alias DD.fx.DragDropHelper.prototypee */
    var prototype = DD.fx.DragDropHelper.prototype;

	/**
	 * Компонент DD.fx.DragSource
	 * @type {DD.fx.DragSource}
	 */
	prototype.DragSource = null;

	/**
	 * Компонент DD.fx.DropTarget
	 * @type {DD.fx.DropTarget}
	 */
	prototype.DropTarget = null;

	/**
	 * Компонент DD.fx.DragScroll
	 * @type {DD.fx.DragScroll}
	 */
	prototype.DragScroll = null;

	/**
	 * Список компонентов DD.fx.ShuffleGrids
	 * @type {DD.fx.ShuffleGrids}
	 */
	prototype.ShuffleGrids = null;

	prototype.enterDocument = function ()
	{
		if (this.DragSource)
		{
			if (this.onCreateImage)
			{
				goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.CREATEIMAGE, this.onCreateImage, false, this);
				this.DragSource.setShowDefaultImage(false);
			};

			this.onGetDragSource  && goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.GETDRAGSOURCE,  this.onGetDragSource,   false, this);
			this.onDragStart      && goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.DRAGSTART,      this.onDragStart,       false, this);
			this.onDragOver       && goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.DRAGOVER,       this.onDragOver,        false, this);
		};

		if (this.DragScroll)
			this.onDragOverScroll && goog.events.listen(this.DragScroll, DD.fx.CustomDragDrop.EventType.DRAGOVERSCROLL, this.onDragOverScroll,  false, this);

		if (this.DropTarget)
		{
			this.onDragEnd        && goog.events.listen(this.DropTarget, DD.fx.CustomDragDrop.EventType.DRAGEND,        this.onDragEnd,         false, this);
			this.onDragDrop       && goog.events.listen(this.DropTarget, DD.fx.CustomDragDrop.EventType.DRAGDROP,       this.onDragDrop,        false, this);
			this.onGetDropTarget  && goog.events.listen(this.DropTarget, DD.fx.CustomDragDrop.EventType.GETDROPTARGET,  this.onGetDropTarget,   false, this);
		};
	};

	/**
	 * Отвязывание событий
	 */
	prototype.exitDocument = function ()
	{
		this.onCreateImage    && goog.events.unlisten(this.DragSource, DD.fx.CustomDragDrop.EventType.CREATEIMAGE,      this.onCreateImage,     false, this);
		this.onGetDragSource  && goog.events.unlisten(this.DragSource, DD.fx.CustomDragDrop.EventType.GETDRAGSOURCE,    this.onGetDragSource,   false, this);
		this.onDragStart      && goog.events.unlisten(this.DragSource, DD.fx.CustomDragDrop.EventType.DRAGSTART,        this.onDragStart,       false, this);
		this.onDragOverScroll && goog.events.unlisten(this.DragScroll, DD.fx.CustomDragDrop.EventType.DRAGOVERSCROLL,   this.onDragOverScroll,  false, this);
		this.onDragEnd        && goog.events.unlisten(this.DropTarget, DD.fx.CustomDragDrop.EventType.DRAGEND,          this.onDragEnd,         false, this);
		this.onDragDrop       && goog.events.unlisten(this.DropTarget, DD.fx.CustomDragDrop.EventType.DRAGDROP,         this.onDragDrop,        false, this);
		this.onGetDropTarget  && goog.events.unlisten(this.DropTarget, DD.fx.CustomDragDrop.EventType.GETDROPTARGET,    this.onGetDropTarget,   false, this);
		this.onDragOver       && goog.events.unlisten(this.DropTarget, DD.fx.CustomDragDrop.EventType.DRAGOVER,         this.onDragOver,        false, this);
	};

	/**
	 * Удаление компонента и списка компонентов в случае, если они созданы
	 */
	prototype.dispose = function()
	{
		this.DragSource && this.DragSource.dispose();
		this.DropTarget && this.DropTarget.dispose();
		this.DragScroll && this.DragScroll.dispose();

		this.exitDocument();
	};

	/**
	 * Получение копии переносимого элемента, который в данный момент виден на странице, так как оригинал скрыт, но тоже присутствует на странице
	 * @return {HTMLElement}
	 */
	prototype.getCopy = function ()
	{
		return this.DragSource.getCopy_();
	};

	/**
	 * Получение образа переносимого элемента
	 * @return {HTMLElement}
	 */
	prototype.getItemImage = function ()
	{
		return this.DragSource.getItemImage();
	};

	/**
	 * Сброс состояния компонента до первоначального
	 */
	prototype.reset = function ()
	{
		this.DragSource.reset();
		this.DropTarget.reset();
		this.DragScroll.reset();
	};

	/**
	 * Устанавливает пользовательский образ переносимого элемента
	 * @param {HTMLElement} value Ссылка на DOM-элемент, которые является пользовательским образом переносимого элемента
	 * @param {Number} 		align Выравнивание образа под курсором во время перемещения
	 */
	prototype.setCustomDragImage = function (value, align)
	{
		this.DragSource.setCustomDragImage(value, align);
	};

	/**
	 * Инициализация компонента DD.fx.DragSource
	 * @param  {HTMLElement} containers Массив DOM-элементов, контейнеров, к которым относится DragSource
	 * @private
	 */
	prototype.initDragSource_ = function (containers)
	{
		this.DragSource = new DD.fx.DragSource({
			pixelThreshold       : this.pixelThreshold_,
			lapseThreshold       : this.lapseThreshold_,
			imageAlign           : this.imageAlign_,
			ignored              : this.ignored_,
			showDefaultImageTime : this.showDefaultImageTime_,
			showDragImage        : this.showDragImage_,
			debugMode            : this.debugMode_,
			dragObjectContainer  : this.dragObjectContainer_
		});

		this.DragSource.setContainer(containers, this.allowClassNames_);
	};

	/**
	 * Инициализация компонента DD.fx.DropTarget
	 * @param  {HTMLElement} containers Массив DOM-элементов, контейнеров, к которым относится DropTarget
	 * @private
	 */
	prototype.initDropTarget_ = function (containers)
	{
		var i = 0,
			ln = containers.length;

		this.DropTarget = new DD.fx.DropTarget({
			pixelThreshold  : this.pixelThreshold_,
			lapseThreshold  : this.lapseThreshold_,
			showDragImage   : this.showDragImage_,
			debugMode       : this.debugMode_
		});

		for (; i < ln; i++)
			this.DropTarget.setContainer(containers[i], this.allowClassNames_);
	};

	/**
	 * Инициализация компонента DD.fx.DragScroll
	 * @param  {HTMLElement} containers Массив DOM-элементов, контейнеров, к которым относится DragScroll
	 * @private
	 */
	prototype.initDragScroll_ = function (containers)
	{
		var i = 0,
			ln = containers.length;

		this.DragScroll = new DD.fx.DragScroll(containers, {
			pixelThreshold    : this.pixelThreshold_,
			lapseThreshold    : this.lapseThreshold_,
			showScrollArea    : this.showScrollArea_,
			scrollParent      : this.scrollParent_,
			scrollParentMode  : this.scrollParentMode_,
			smoothScroll      : this.smoothScroll_,
			debugMode         : this.debugMode_
		});
	};

	prototype.setScrollAreaHideByAxis = function (value)
	{
		this.DragScroll && this.DragScroll.setScrollAreaHideByAxis(value);
	};

	prototype.setScrollAreaShowByAxis = function (value)
	{
		this.DragScroll && this.DragScroll.setScrollAreaShowByAxis(value);
	};

	/**
	 * Инициализация компонента DD.fx.ShuffleGrid
	 * @param  {Array} array Массив DOM-элементов
	 * @private
	 */
	prototype.initShuffleGrid_ = function (array)
	{
		var i = 0,
			ln = array.length;

		this.ShuffleGrids = [];
		for (; i < ln; i++)
			this.ShuffleGrids.push(new DD.fx.ShuffleGrid(
			{
				container      : array[i][0],
				target         : array[i][1],
				gridGutter     : this.gridGutter_,
				classname      : this.allowClassNames_,
				dropZoneTime   : this.dropZoneTime_,
				debugMode      : this.debugMode_
			}));
	};

	/**
	 * Связывание компонентов посредством событий
	 * @private
	 */
	prototype.installEventDependence_ = function ()
	{
		if (this.DragSource)
		{
			goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.GETDRAGSOURCE, function(event)
			{
				this.DropTarget && this.DropTarget.onGetDragSource(event);
			}, false, this);

			goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.DRAGSTART, function(event)
			{
				this.DragScroll && this.DragScroll.onDragStart(event);
				this.DropTarget && this.DropTarget.onDragStart(event);
			}, false, this);

			goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.DRAGOVER, function(event)
			{
				this.DragScroll && this.DragScroll.onDragOver(event);
			}, false, this);

			goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.DRAGEND, function(event)
			{
				this.DragScroll && this.DragScroll.cancel();
			}, false, this);
		};

		// Добавление элемента перетаскиваемого элемента в новый контейнер
		if (this.DropTarget)
			goog.events.listen(this.DropTarget, DD.fx.CustomDragDrop.EventType.DRAGDROP, function(event)
			{
				if (event.dropArea && (event.dropArea.children.length == 0))
					event.dragSource && event.dropArea.appendChild(event.dragSource);
			});

		var countShuffleGrids = this.ShuffleGrids ? this.ShuffleGrids.length : 0;
		for (var i = 0; i < countShuffleGrids; i++)
		{
			var ShuffleGrid = this.ShuffleGrids[i];

			if (this.DropTarget)
			{
				goog.events.listen(this.DropTarget, DD.fx.CustomDragDrop.EventType.DRAGOVER, function(event)
				{
					this.onDragOver(event);
				}, false, ShuffleGrid);

				goog.events.listen(this.DropTarget, DD.fx.CustomDragDrop.EventType.DRAGDROP, function(event)
				{
					this.onDragDrop(event);
				}, false, ShuffleGrid);
			};

			if (this.DragSource)
			{
				goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.GETDRAGSOURCE, function(event)
				{
					this.onGetDragSource(event);
				}, false, ShuffleGrid);

				goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.DRAGSTART, function(event)
				{
					this.onDragStart(event);
				}, false, ShuffleGrid);

				goog.events.listen(this.DragSource, DD.fx.CustomDragDrop.EventType.DRAGEND, function(event)
				{
					this.cancel(event);
				}, false, ShuffleGrid);

			};

			if (this.DragScroll)
			{
				goog.events.listen(this.DragScroll, DD.fx.CustomDragDrop.EventType.DRAGOVER, function(event)
				{
					ShuffleGrid.breakDropOverScrolling(event.isScroll);
				}, false, ShuffleGrid);
			};
		};
	};
}); // goog.scoope


text:
<?php
require_once ('mercadopago.php');

$mp = new MP('ACCESS_TOKEN');

$payment_data = array(
	"status" => "cancelled"
);

$payment = $mp->put("/v1/payments/PAYMENT_ID", $payment_data);


text:
suite("ClientGui:", function() {
	var sut;
	var stuckKeysHandler;
	var inputmanager;

	setup(function() {
		stuckKeysHandler = new wdi.StuckKeysHandler();
		inputmanager = {
			manageChar: function() {},
			getValue: function() {},
			enable: function() {},
			disable: function() {},
			setCurrentWindow: function() {}
		};
		sut = new wdi.ClientGui({stuckKeysHandler: stuckKeysHandler, inputManager: inputmanager});
	});

	test('releaseAllKeys calls stuckKeysHandler.releaseAllKeys', sinon.test(function() {
		this.mock(stuckKeysHandler)
			.expects('releaseAllKeys')
			.once()
			.withExactArgs();
		sut.releaseAllKeys();
	}));

	test('fillSubCanvas called with filterPosition will call to CollisionDetector thereIsBoxCollition', sinon.test(function() {
		addFakeMainCanvas();
		addFakeSubCanvas(0, 0, 0, 100, 100);
		configureDrawSubCanvasAsStub(this);
		var filterPosition = {
			top:0,
			left:50,
			right:100,
			bottom:100
		};
		this.mock(wdi.CollisionDetector).expects("thereIsBoxCollision").once().withExactArgs({
			top:0,
			left:0,
			right:100,
			bottom:100
		}, filterPosition);
		sut.fillSubCanvas(filterPosition);
	}));

	test('fillSubCanvas called with filterPosition and position collides with subcanvas will call to drawSubCanvas with correct data', sinon.test(function() {
		var mainCanvas = addFakeMainCanvas();
		var subCanvas = addFakeSubCanvas(0,0,100,100);
		configureCollisionDetectorAsStub(this,true);
		this.mock(sut).expects('_doDrawSubCanvas').once().withExactArgs(mainCanvas, subCanvas, subCanvas.info);
		sut.fillSubCanvas();
	}));

	test('fillSubCanvas called with filterPosition and position collides with subcanvas will not call to drawSubCanvas', sinon.test(function(){
		addFakeMainCanvas();
		addFakeSubCanvas(0,0,100,100);
		configureCollisionDetectorAsStub(this,false);
		this.mock(sut).expects('_doDrawSubCanvas').never();
		sut.fillSubCanvas({top:500,left:500,botton:600,right:600});
	}));

	var configureCollisionDetectorAsStub = function(self, thereIsCollision) {
		self.stub(wdi.CollisionDetector, "thereIsBoxCollision", function(){
			return thereIsCollision;
		});
	};

	var configureDrawSubCanvasAsStub = function(self) {
		self.stub(sut, "_doDrawSubCanvas", function(){});
	};

	var addFakeMainCanvas = function() {
		var mainCanvas = constructFakeCanvas(0, 0, 1024, 768);
		sut.canvas[0] = mainCanvas;
		return mainCanvas;
	};

	var addFakeSubCanvas = function(id, top, left, width, height) {
		var subCanvas = constructFakeCanvas(top, left, width, height);
		sut.subCanvas[id] = subCanvas;
		return subCanvas;
	};

	var constructFakeWindow = function(top, left, width, height) {
		return {
			top: top,
			left: left,
			width: width,
			height: height
		}
	};

	var constructFakeCanvas = function(top, left, width, height) {
		return {
			info: constructFakeWindow(top, left, width, height)
		};
	};

	suite('#generateEvent', function () {
		var event = 'keyEvent';
		var keyCode = 'fake keyCode';
		var params = [ { keyCode: keyCode } ];

		function execute () {
			sut.generateEvent(event, params);
		}

		test('Should get the value of the input when is a key event', sinon.test(function () {
			this.stub(inputmanager, 'manageChar');
			this.mock(inputmanager)
				.expects('getValue')
				.once()
				.withExactArgs()
				.returns("a");
			execute();
		}));

		test('Should manage the params of the event when there is a value with length = 1 and is a key event', sinon.test(function () {
			this.stub(inputmanager, 'getValue').returns('a');
			this.mock(inputmanager)
				.expects('manageChar')
				.once()
				.withExactArgs('a', params);
			execute();
		}));

		test('Should not manage the params when there is no value when is a key event', sinon.test(function () {
			this.stub(inputmanager, 'getValue').returns("");
			this.mock(inputmanager)
				.expects('manageChar')
				.never();
			execute();
		}));

		test('Should check if a special key has been pressed when is a key event', sinon.test(function () {
			this.stub(inputmanager, 'getValue').returns("");
			this.mock(stuckKeysHandler)
				.expects('checkSpecialKey')
				.once()
				.withExactArgs(event, keyCode);
			execute();
		}));
	});

	suite('#disableKeyboard', function () {
		test('Should call to inputManager.disable', sinon.test(function () {
			this.mock(inputmanager)
				.expects('disable')
				.once()
				.withExactArgs();
			sut.disableKeyboard();
		}));
	});

	suite('#enableKeyboard', function () {
		test('Should call to inputManager.enable', sinon.test(function () {
			this.mock(inputmanager)
				.expects('enable')
				.once()
				.withExactArgs();
			sut.enableKeyboard();
		}));
	});

});


text:
Implements a simple event broker for simpy, utilizing named channels for separating traffic.

## Purpose
Simpy includes a filtered pipe concept that requires a filter be provided to the pipe. This concept removes the need to check the filter so many times, since the subscriptions are grouped together by channels, or topics. Whenever a topic is published to, anyone on it will receive the event message.

This was based off of the [Broadcast Pipe](http://simpy.readthedocs.org/en/latest/examples/process_communication.html) example from the simpy docs.

## How To
If you run the broker file directly, there is a simple example included. This example includes a `Consumer` that represents your modeled component that will subscribe to the topic. Run the example with:
```
python event_broker.py
```
This should result in the output of:
```
Active
Down
Active
```


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Activity Schema
 */
var ActivitySchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  description: {
    short: {
      type: String,
      default: '',
      trim: true,
      required: 'Short description cannot be blank'
    },
    long: {
      type: String,
      default: '',
      trim: true,
      required: 'Long description cannot be blank'
    }
  },
  duration: {
    startDate: {
      type: Date,
      default: Date.now,
      required: 'Start cannot be blank'
    },
    endDate: {
      type: Date,
      default: Date.now,
      required: 'Start cannot be blank'
    }
  },
  location: {
    latlng: {
      type: [Number],
      default: [0, 0],
      required: 'Please fill coordinates'
    }
  },
  modified: {
    type: Date,
    default: Date.now
  },
  title: {
    type: String,
    default: '',
    trim: true,
    required: 'Title cannot be blank'
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  }
});

mongoose.model('Activity', ActivitySchema);


text:
![Microsoft patterns & practices](http://pnp.azurewebsites.net/images/pnp-logo.png)
# IoT Journey
_An exploration into building a solution in the cloud_

[![Build status](https://ci.appveyor.com/api/projects/status/7oj0ufqarqmgfqim/branch/master?svg=true)](https://ci.appveyor.com/project/mspnp/iot-journey)

[![Join the chat at https://gitter.im/mspnp/iot-journey](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mspnp/iot-journey?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

**There will be limited activity on this project until late September 2015.**

## Why

There is no one-size-fits-all answer when it comes to building an [IoT solution][intro-to-iot].
Our approach to guidance is to embark on a collaborative journey into
understanding the mechanics and challenges surrounding an end-to-end system.
Our purpose is _not_ to tell you all the answers that you'll need, but rather
to help you ask the right questions.

## What

We will be constructing an IoT solution hosted in Azure.
Our focus will be on problems related to the back-end architecture, such as:
- high-scale event ingestion
- event stream processing
- facilitation of analysis

We have identified a number of high-level scenarios; described and explored in the [docs][/docs]. We will be using the same tools and services that are available to you.
We are creating a set of _reference implementations_ (our fancy name for an
end-to-end sample). Some of the reference implementation are meant to work in concert while others are alternative implementations.

In addition to the **source code**, we'll also produce a **set of written
articles** covering the general concepts and patterns, the rationale behind
design choices, and a few other things to help you navigate the guidance.

We intend this to be an interactive act of discovery.

## How

We are basing our scenarios on requirements we've gathered from customers and advisors. The scenario is not meant to be realistic, but rather representative. That is, it should represent the most common needs and [challenges][] encountered in this space.

We are very interested in your feedback. We are publishing updates about the work on [our video blog](https://channel9.msdn.com/blogs/mspnp). We encourage you to ask questions in the chat room or to open issue on this repo.
Any and all feedback is welcome.

## Who

Our intended audience for this guidance is any senior developer or architect interested in developing an IoT solution.
We want all developers, regardless of their preferred development stack, to benefit from the written guidance.
If you feel that there is anything more that we can do to make this guidance accessible to a broader audience, you are encouraged to share.

## Next Step

- Go to the [docs](docs) folder, review the readme, and begin reviewing the content.

## Problems, Concerns, and Feedback
If something doesn't make sense, start with the [FAQ](FAQ.md).
If that doesn't help join the conversation on gitter or open an issues.
If you want to contribute directly, please review our
[contribution guidelines](CONTRIBUTING.md).

[![Join the chat at https://gitter.im/mspnp/iot-journey](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mspnp/iot-journey?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

| Current Backlog Status
| :------
| [![Ready](https://badge.waffle.io/mspnp/iot-journey.svg?label=ready&title=Ready)](https://waffle.io/mspnp/iot-journey)
| [![In Progress](https://badge.waffle.io/mspnp/iot-journey.svg?label=in progress&title=In Progress)](https://waffle.io/mspnp/iot-journey)
| [![Awaiting Review](https://badge.waffle.io/mspnp/iot-journey.svg?label=awaiting-review&title=Awaiting Review)](https://waffle.io/mspnp/iot-journey)

[intro-to-iot]: docs/01-what-is-an-IoT-solution.md


text:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <title>Babylon - Getting Started</title>
    <!--- link to the last version of babylon --->
    <script src="babylon.2.5.js"></script>
    <style>
        html, body {
            overflow: hidden;
            width   : 100%;
            height  : 100%;
            margin  : 0;
            padding : 0;
        }

        #renderCanvas {
            width   : 100%;
            height  : 100%;
            touch-action: none;
        }
    </style>
</head>
<body>
    <canvas id="renderCanvas"></canvas>
    <script src="../libs/performance.js"></script>
    <script src="../libs/stats.min.js"></script>
    <script>
        window.addEventListener('DOMContentLoaded', function(){
            var stats = new Stats();
            stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
            document.body.appendChild(stats.dom);

            var canvas = document.getElementById('renderCanvas'),

                angle = 0.01,

                engine = new BABYLON.Engine(canvas, true),

                box = null;

            // createScene function that creates and return the scene
            var createScene = function(){
                // create a basic BJS Scene object
                var scene = new BABYLON.Scene(engine);

                // create a FreeCamera, and set its position to (x:0, y:5, z:-10)
                var camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 5,-10), scene);

                // target the camera to scene origin
                camera.setTarget(BABYLON.Vector3.Zero());

                // attach the camera to the canvas
                camera.attachControl(canvas, false);

                // create a basic light, aiming 0,1,0 - meaning, to the sky
                var light = new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(0,1,0), scene);

                var materialBox = new BABYLON.StandardMaterial("texture3", scene);
                materialBox.diffuseTexture = new BABYLON.Texture("../textures/crate.gif", scene);

                box = BABYLON.Mesh.CreateBox("box", 3.0, scene);

                box.material = materialBox;

                // return the created scene
                return scene;
            }

            // call the createScene function
            var scene = createScene();

            // run the render loop
            engine.runRenderLoop(function(){
                box.rotation.x += angle;
                box.rotation.y += angle;
                scene.render();
                stats.update();
            });

            // the canvas/window resize event handler
            window.addEventListener('resize', function(){
                engine.resize();
            });
        });
    </script>
</body>
</html>


text:
package uk.ac.cam.caret.sakai.rwiki.component.service.impl;

import org.apache.fop.apps.MimeConstants;

public class FOP2PDFSerializer extends BaseFOPSerializer
{

	public FOP2PDFSerializer()
	{
		mimeType = MimeConstants.MIME_PDF;
	}

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="google-site-verification" content="6F4OqKmDkxMqUtTjTSCN1qPy2-m1_HN_H_aGMQkeZrA" />

  <title>Archives: 3/2017: 2017</title>

      <link rel="stylesheet" href="/css/hexo-uno.css">

  <link rel="stylesheet" href="/css/uno.css">
  <link rel="stylesheet" href="/css/main.css">
  <link rel="stylesheet" href="//cdn.bootcss.com/highlight.js/9.2.0/styles/github.min.css">

Helkay

不忘初心,方得始终。

首页

归档

标签

目录

                  GitHub

                  Email

          quartz定时功能

          <time datetime="Fri Mar 24 2017 00:00:00 GMT+0800" class="post-list__meta--date date">2017-03-24</time> •
          on

                 定时器

          签名与加密技术

          <time datetime="Thu Mar 23 2017 00:00:00 GMT+0800" class="post-list__meta--date date">2017-03-23</time> •
          on

                 Java

          Maven学习笔记

          <time datetime="Thu Mar 16 2017 00:00:00 GMT+0800" class="post-list__meta--date date">2017-03-16</time> •
          on

                 Maven

          mysql数据库无法插入中文

          <time datetime="Fri Mar 10 2017 00:00:00 GMT+0800" class="post-list__meta--date date">2017-03-10</time> •
          on

                 Mysql

      Page 1 of 1


text:
#ifndef __INC_MODE_H__
#define __INC_MODE_H__

#define MAX_MODES 256

typedef struct u_listent u_listent;
typedef struct u_mode_info u_mode_info;
typedef struct u_mode_ctx u_mode_ctx;
typedef struct u_mode_stacker u_mode_stacker;
typedef struct u_modes u_modes;
typedef struct u_mode_buf_stack u_mode_buf_stack;

#define MAXBANLIST  50

struct u_listent {
	char mask[256];
	char setter[256];
	u_ts_t time;
	mowgli_node_t n;
};

#include "msg.h"

typedef enum u_mode_type {
	MODE_EXTERNAL,
	MODE_STATUS,
	MODE_FLAG,
	MODE_LIST,
} u_mode_type;

#define MODE_OPER_ONLY         0x0001 /* need oper to change */
#define MODE_NO_RESET          0x0002 /* cannot unset the mode */
#define MODE_NO_SET            0x0004 /* cannot set the mode */

#define MODE_NO_CHANGE  (MODE_NO_RESET | MODE_NO_SET) /* cannot change the mode */

struct u_mode_info {
	char ch;
	u_mode_type type;
	ulong flags;

	union {
		int (*fn)(u_modes*, int on, char *arg);
		ulong data;
	} arg;
};

struct u_mode_ctx {
	u_mode_info *infotab;

	ulong (*get_flag_bits)(u_modes*);
	bool (*set_flag_bits)(u_modes*, ulong); /* |= */
	bool (*reset_flag_bits)(u_modes*, ulong); /* &= ~ */

	void *(*get_status_target)(u_modes*, char*);
	bool (*set_status_bits)(u_modes*, void *tgt, ulong);
	bool (*reset_status_bits)(u_modes*, void *tgt, ulong);

	mowgli_list_t *(*get_list)(u_modes*, u_mode_info*);

	void (*sync)(u_modes*);
};

struct u_mode_stacker {
	void (*start)(u_modes*);
	void (*end)(u_modes*);

	void (*put_external)(u_modes*, int on, char *param);
	void (*put_status)(u_modes*, int on, void *tgt);
	void (*put_flag)(u_modes*, int on);
	void (*put_listent)(u_modes*, int on, u_listent*);

	void (*send_list)(u_modes*);
};

#define MODE_FORCE_ALL   0x0001

#define MODE_ERR_UNK_CHAR         0x0001
#define MODE_ERR_NO_ACCESS        0x0002
#define MODE_ERR_NOT_OPER         0x0004
#define MODE_ERR_MISSING_PARAM    0x0008
#define MODE_ERR_LIST_FULL        0x0010

struct u_modes {
	u_mode_ctx *ctx;
	u_mode_stacker *stacker;
	u_sourceinfo *setter;
	void *target;
	void *access;
	ulong flags;

	u_mode_info *info;

	ulong errors;
	char unk[MAX_MODES+1];
	void *stack; /* private use, by stacker */
};

/* extracts only the flags from a mode string. no callbacks */
extern void u_mode_flags(u_mode_ctx*, char*, ulong *set, ulong *reset);

/* processes modes, performing all callbacks */
extern int u_mode_process(u_modes *m, int parc, char **parv);

static inline void u_mode_put(u_modes *m, int on, char *param)
{
	if (m && m->stacker && m->stacker->put_external)
		m->stacker->put_external(m, on, param);
}

static inline bool u_mode_has_access(u_modes *m)
{
	if (!m->access && !(m->flags & MODE_FORCE_ALL)) {
		m->errors |= MODE_ERR_NO_ACCESS;
		return false;
	}

	return true;
}

/* simple buffered mode stacker. provides put_external, put_flag, and
   put_listent, but sending the result must be handled by the user. */
extern u_mode_stacker u_mode_buf_stacker;
struct u_mode_buf_stack {
	int on;
	char *c, cbuf[512];
	char *d, dbuf[512];
};

#endif