code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
HardwareSerial.h - Hardware serial library for Wiring
Copyright (c) 2006 Nicholas Zambetti. All right reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef HardwareSerial_h
#define HardwareSerial_h
#include <inttypes.h>
#include "Print.h"
struct ring_buffer;
#if defined(__AVR_ATmega103__)
class HardwareSerial : public Print
{
private:
ring_buffer *_rx_buffer;
volatile uint8_t *_ubrr;
volatile uint8_t *_ucr;
volatile uint8_t *_usr;
volatile uint8_t *_udr;
uint8_t _rxen;
uint8_t _txen;
uint8_t _rxcie;
uint8_t _udre;
public:
HardwareSerial(ring_buffer *rx_buffer,
volatile uint8_t *ubrr,
volatile uint8_t *ucr, volatile uint8_t *usr,
volatile uint8_t *udr,
uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre);
void begin(long);
void end();
uint8_t available(void);
int read(void);
void flush(void);
virtual void write(uint8_t);
using Print::write; // pull in write(str) and write(buf, size) from Print
};
#else
class HardwareSerial : public Print
{
private:
ring_buffer *_rx_buffer;
volatile uint8_t *_ubrrh;
volatile uint8_t *_ubrrl;
volatile uint8_t *_ucsra;
volatile uint8_t *_ucsrb;
volatile uint8_t *_udr;
uint8_t _rxen;
uint8_t _txen;
uint8_t _rxcie;
uint8_t _udre;
uint8_t _u2x;
public:
HardwareSerial(ring_buffer *rx_buffer,
volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
volatile uint8_t *udr,
uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x);
void begin(long);
void end();
uint8_t available(void);
int read(void);
void flush(void);
virtual void write(uint8_t);
using Print::write; // pull in write(str) and write(buf, size) from Print
};
#endif
extern HardwareSerial Serial;
#if defined(__AVR_ATmega1280__)
extern HardwareSerial Serial1;
extern HardwareSerial Serial2;
extern HardwareSerial Serial3;
#endif
#endif
| chcbaram/FPGA | zap-2.3.0-windows/papilio-zap-ide/hardware/papilio/avr8/cores/arduino/HardwareSerial.h | C | mit | 2,713 |
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as courseActions from '../../actions/courseActions';
import CourseForm from './CourseForm';
import {authorsFormattedForDropdown} from '../../selectors/selectors';
import toastr from 'toastr';
export class ManageCoursePage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
course: Object.assign({}, props.course),
errors: {},
saving: false
};
this.updateCourseState = this.updateCourseState.bind(this);
this.saveCourse = this.saveCourse.bind(this);
}
componentWillReceiveProps(nextProps) {
if (this.props.course.id != nextProps.course.id) {
// Necessary to populate form when existing course is loaded directly.
this.setState({course: Object.assign({}, nextProps.course)});
}
}
updateCourseState(event) { // handler for each form field
const field = event.target.name;
let course = this.state.course;
course[field] = event.target.value;
return this.setState({course: course});
}
courseFormValid() {
let formIsValid = true;
let errors = {};
if (this.state.course.title.length < 5) {
errors.title = 'Title must be at least 5 characters.';
formIsValid = false;
}
this.setState({errors: errors});
return formIsValid;
}
saveCourse(event) {
event.preventDefault();
if (!this.courseFormValid()) {
return;
}
this.setState({saving: true});
this.props.actions.saveCourse(this.state.course)
.then(() => this.redirect())
.catch(error => {
toastr.error(error);
this.setState({saving: false});
});
}
redirect() {
// redirect to courses route
this.setState({saving: false});
toastr.success('Course saved!');
this.context.router.push('/courses');
}
render() {
return (
<CourseForm allAuthors={this.props.authors}
onChange={this.updateCourseState}
onSave={this.saveCourse}
errors={this.state.errors}
course={this.state.course}
saving={this.state.saving}/>
);
}
}
ManageCoursePage.propTypes = {
course: PropTypes.object.isRequired,
authors: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
};
//Pull in the React Router context so router is available on this.context.router.
ManageCoursePage.contextTypes = {
router: PropTypes.object
};
function getCourseById(courses, id) {
const course = courses.filter(course => course.id == id);
if (course.length) return course[0]; //since filter returns an array, have to grab the first.
return null;
}
function mapStateToProps(state, ownProps) {
let course = {
id: "",
title: "",
watchHref: "",
authorId: "",
length: "23",
category: ""
};
const courseId = ownProps.params.id; // from the path `/course/:id`
if (courseId && state.courses.length > 0) {
course = getCourseById(state.courses, courseId);
}
return {
course: course,
authors: authorsFormattedForDropdown(state.authors)
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(courseActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(ManageCoursePage);
| vitaliykrushinsky/react-redux-demo | src/components/course/ManageCoursePage.js | JavaScript | mit | 3,176 |
.sessionForm{
padding: 10px;
}
.carapaceForm{
padding: 10px;
border: 3px solid #000000;
min-width: 960px;
margin-bottom: 10px;
}
label{
margin: 5px;
}
input{
margin: 5px;
}
button{
margin: 5px;
}
.section{
border: 1px solid #000000;
margin-bottom: 10px;
}
.carapaceSection{
padding: 10px;
background-color #eeeeee;
}
.itemForm{
padding: 10px;
border: 3px solid #000000;
}
.selectedItem{
padding: 10px;
border: 3px solid #000000;
}
.itemSection{
padding: 10px;
background-color #eeeeee;
}
.prospit{
background-color:black;
}
.derse{
background-color: white;
} | jadedResearcher/SBURBSimulator | web/css/sessionCustomizer.css | CSS | mit | 648 |
AmazonTemplateDescriptionCategorySpecificGridRowRenderer = Class.create(AmazonTemplateDescriptionCategorySpecificRenderer, {
// ---------------------------------------
attributeHandler: null,
// ---------------------------------------
process: function()
{
if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) {
return '';
}
if (!this.load()) {
return '';
}
this.renderParentSpecific();
if (this.specificHandler.isSpecificRendered(this.indexedXPath) && !this.isValueForceSet()) {
return '';
}
if (this.specificHandler.isSpecificRendered(this.indexedXPath)) {
if (this.isValueForceSet()) {
this.forceSelectAndDisable(this.getForceSetValue());
this.hideButton($(this.indexedXPath + '_remove_button'));
var myEvent = new CustomEvent('undeleteble-specific-appear');
$(this.getParentIndexedXpath()).dispatchEvent(myEvent);
}
return '';
}
this.renderSelf();
if (this.isValueForceSet()) {
this.forceSelectAndDisable(this.getForceSetValue());
}
this.observeToolTips(this.indexedXPath);
this.checkSelection();
this.renderSpecificAttributes();
},
// ---------------------------------------
load: function($super)
{
this.attributeHandler = AttributeHandlerObj;
return $super();
},
//########################################
renderParentSpecific: function()
{
if (this.specific.parent_specific_id == null) {
return '';
}
if (!this.dictionaryHelper.isSpecificTypeContainer(this.parentSpecific)) {
return '';
}
var parentBlockRenderer = new AmazonTemplateDescriptionCategorySpecificBlockRenderer();
parentBlockRenderer.setSpecificsHandler(this.specificHandler);
parentBlockRenderer.setIndexedXpath(this.getParentIndexedXpath());
parentBlockRenderer.process();
},
renderSelf: function()
{
this.renderLabel();
this.renderChooseMode();
this.renderValueInputs();
// affects the appearance of the actions buttons
this.specificHandler.markSpecificAsRendered(this.indexedXPath);
this.renderButtons();
// ---------------------------------------
$(this.indexedXPath).observe('my-duplicate-is-rendered', this.onMyDuplicateRendered.bind(this));
// ---------------------------------------
// like grid visibility or view of 'Add Specific' container
this.throwEventsToParents();
},
renderSpecificAttributes: function()
{
var self = this;
if (!this.specific.params.hasOwnProperty('attributes')) {
return '';
}
this.specific.params.attributes.each(function(attribute, index) {
var renderer = new AmazonTemplateDescriptionCategorySpecificGridRowAttributeRenderer();
renderer.setSpecificsHandler(self.specificHandler);
renderer.setIndexedXpath(self.indexedXPath);
renderer.attribute = attribute;
renderer.attributeIndex = index;
renderer.process();
});
},
//########################################
renderLabel: function()
{
var td = new Element('td');
var title = this.specific.title;
if (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) {
title += ' <span class="required">*</span>';
} else if (this.dictionaryHelper.isSpecificDesired(this.specific)) {
title += ' <span style="color: grey; font-style: italic;">(' + M2ePro.translator.translate('Desired') + ')</span>';
}
td.appendChild((new Element('span').insert(title)));
var note = this.getDefinitionNote(this.specific.data_definition);
if (note) {
var toolTip = this.getToolTipBlock(this.indexedXPath + '_definition_note', note);
toolTip.show();
td.appendChild(toolTip);
}
var notice = this.getSpecificOverriddenNotice();
if (notice) td.appendChild(notice);
notice = this.getSpecificParentageNotice();
if (notice) td.appendChild(notice);
this.getRowContainer().appendChild(td);
},
// ---------------------------------------
renderChooseMode: function()
{
var select = new Element('select', {
'id' : this.indexedXPath +'_mode',
'indexedxpath': this.indexedXPath,
'class' : 'M2ePro-required-when-visible',
'style' : 'width: 93.2%;'
});
select.appendChild(new Element('option', {'style': 'display: none'}));
if (this.specific.recommended_values.length > 0) {
select.appendChild(new Element('option', {'value': this.MODE_RECOMMENDED_VALUE}))
.insert(M2ePro.translator.translate('Recommended Values'));
}
select.appendChild(new Element('option', {'value': this.MODE_CUSTOM_VALUE}))
.insert(M2ePro.translator.translate('Custom Value'));
select.appendChild(new Element('option', {'value': this.MODE_CUSTOM_ATTRIBUTE}))
.insert(M2ePro.translator.translate('Custom Attribute'));
select.observe('change', this.onChangeChooseMode.bind(this));
this.getRowContainer().appendChild(new Element('td')).appendChild(select);
},
onChangeChooseMode: function(event)
{
var customValue = $(this.indexedXPath + '_' + this.MODE_CUSTOM_VALUE),
customValueNote = $(this.indexedXPath + '_custom_value_note'),
customValueNoteError = $('advice-M2ePro-specifics-validation-' + customValue.id);
var customAttribute = $(this.indexedXPath + '_' + this.MODE_CUSTOM_ATTRIBUTE),
customAttributeNote = $(this.indexedXPath + '_custom_attribute_note'),
customAttributeError = $('advice-M2ePro-required-when-visible-' + customAttribute.id);
var recommendedValue = $(this.indexedXPath + '_' + this.MODE_RECOMMENDED_VALUE);
customValue && customValue.hide();
customValueNote && customValueNote.hide();
customValueNoteError && customValueNoteError.hide();
customAttribute && customAttribute.hide();
customAttributeNote && customAttributeNote.hide();
customAttributeError && customAttributeError.hide();
recommendedValue && recommendedValue.hide();
if (event.target.value == this.MODE_CUSTOM_VALUE) {
customValue && customValue.show();
customValueNote && customValueNote.show();
customValueNoteError && customValueNoteError.show();
}
if (event.target.value == this.MODE_CUSTOM_ATTRIBUTE) {
customAttribute && customAttribute.show();
customAttributeNote && customAttributeNote.show();
customAttributeError && customAttributeError.show();
}
if (event.target.value == this.MODE_RECOMMENDED_VALUE) {
recommendedValue && recommendedValue.show();
}
},
// ---------------------------------------
renderValueInputs: function()
{
var td = this.getRowContainer().appendChild(new Element('td'));
// ---------------------------------------
if (this.dictionaryHelper.isSpecificTypeText(this.specific)) {
var note = this.getCustomValueTypeNote();
if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '_custom_value_note', note));
td.appendChild(this.getTextTypeInput());
}
if (this.dictionaryHelper.isSpecificTypeSelect(this.specific)) {
td.appendChild(this.getSelectTypeInput());
}
// ---------------------------------------
// ---------------------------------------
note = this.getCustomAttributeTypeNote();
if (note) td.appendChild(this.getToolTipBlock(this.indexedXPath + '_custom_attribute_note', note));
td.appendChild(this.getCustomAttributeSelect());
// ---------------------------------------
td.appendChild(this.getRecommendedValuesSelect());
},
// ---------------------------------------
getTextTypeInput: function()
{
if (this.dictionaryHelper.isSpecificTypeTextArea(this.specific)) {
var input = new Element('textarea', {
'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE,
'indexedxpath' : this.indexedXPath,
'specific_id' : this.specific.specific_id,
'specific_type' : this.specific.params.type,
'mode' : this.MODE_CUSTOM_VALUE,
'class' : 'M2ePro-required-when-visible M2ePro-specifics-validation',
'style' : 'width: 91.4%; display: none;'
});
} else {
var input = new Element('input', {
'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE,
'indexedxpath' : this.indexedXPath,
'specific_id' : this.specific.specific_id,
'mode' : this.MODE_CUSTOM_VALUE,
'specific_type' : this.specific.params.type,
'type' : 'text',
'class' : 'input-text M2ePro-required-when-visible M2ePro-specifics-validation',
'style' : 'display: none; width: 91.4%;'
});
this.specific.params.type == 'date_time' && Calendar.setup({
'inputField': input,
'ifFormat': "%Y-%m-%d %H:%M:%S",
'showsTime': true,
'button': input,
'align': 'Bl',
'singleClick': true
});
this.specific.params.type == 'date' && Calendar.setup({
'inputField': input,
'ifFormat': "%Y-%m-%d",
'showsTime': true,
'button': input,
'align': 'Bl',
'singleClick': true
});
}
input.observe('change', this.onChangeValue.bind(this));
return input;
},
getSelectTypeInput: function()
{
var self = this;
var select = new Element('select', {
'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE,
'indexedxpath': this.indexedXPath,
'specific_id' : this.specific.specific_id,
'mode' : this.MODE_CUSTOM_VALUE,
'class' : 'M2ePro-required-when-visible',
'style' : 'display: none; width: 93.2%;'
});
select.appendChild(new Element('option', {'style': 'display: none;'}));
var specificOptions = this.specific.values;
specificOptions.each(function(option) {
var label = option == 'true' ? 'Yes' : (option == 'false' ? 'No' : option),
tempOption = new Element('option', {'value': option});
select.appendChild(tempOption).insert(label);
});
select.observe('change', this.onChangeValue.bind(this));
return select;
},
getCustomAttributeSelect: function()
{
var select = new Element('select', {
'id' : this.indexedXPath +'_'+ this.MODE_CUSTOM_ATTRIBUTE,
'indexedxpath' : this.indexedXPath,
'specific_id' : this.specific.specific_id,
'specific_type' : this.specific.params.type,
'mode' : this.MODE_CUSTOM_ATTRIBUTE,
'class' : 'attributes M2ePro-required-when-visible',
'style' : 'display: none; width: 93.2%;',
'apply_to_all_attribute_sets' : '0'
});
select.appendChild(new Element('option', {'style': 'display: none', 'value': ''}));
this.attributeHandler.availableAttributes.each(function(el) {
select.appendChild(new Element('option', {'value': el.code})).insert(el.label);
});
select.value = '';
select.observe('change', this.onChangeValue.bind(this));
var handlerObj = new AttributeCreator(select.id);
handlerObj.setSelectObj(select);
handlerObj.injectAddOption();
return select;
},
getRecommendedValuesSelect: function()
{
var select = new Element('select', {
'id' : this.indexedXPath +'_'+ this.MODE_RECOMMENDED_VALUE,
'indexedxpath': this.indexedXPath,
'specific_id' : this.specific.specific_id,
'mode' : this.MODE_RECOMMENDED_VALUE,
'class' : 'M2ePro-required-when-visible',
'style' : 'display: none; width: 93.2%;'
});
select.appendChild(new Element('option', {'style': 'display: none', 'value': ''}));
this.specific.recommended_values.each(function(value) {
select.appendChild(new Element('option', {'value': value})).insert(value);
});
select.value = '';
select.observe('change', this.onChangeValue.bind(this));
return select;
},
onChangeValue: function(event)
{
var selectedObj = {};
selectedObj['mode'] = event.target.getAttribute('mode');
selectedObj['type'] = event.target.getAttribute('specific_type');
selectedObj['is_required'] = (this.dictionaryHelper.isSpecificRequired(this.specific) || this.isValueForceSet()) ? 1 : 0;
selectedObj[selectedObj.mode] = event.target.value;
this.specificHandler.markSpecificAsSelected(this.indexedXPath, selectedObj);
},
// ---------------------------------------
renderButtons: function()
{
var td = this.getRowContainer().appendChild(new Element('td'));
var cloneButton = this.getCloneButton();
if(cloneButton !== null) td.appendChild(cloneButton);
var removeButton = this.getRemoveButton();
if(removeButton !== null) td.appendChild(removeButton);
},
// ---------------------------------------
throwEventsToParents: function()
{
var myEvent,
parentXpath;
// ---------------------------------------
myEvent = new CustomEvent('child-specific-rendered');
parentXpath = this.getParentIndexedXpath();
$(parentXpath + '_grid').dispatchEvent(myEvent);
$(parentXpath + '_add_row').dispatchEvent(myEvent);
// ---------------------------------------
// my duplicate is already rendered
this.touchMyNeighbors();
// ---------------------------------------
// ---------------------------------------
if (this.isValueForceSet()) {
this.hideButton($(this.indexedXPath + '_remove_button'));
myEvent = new CustomEvent('undeleteble-specific-appear');
$(this.getParentIndexedXpath()).dispatchEvent(myEvent);
}
// ---------------------------------------
},
//########################################
checkSelection: function()
{
if (this.specific.values.length == 1) {
this.forceSelectAndDisable(this.specific.values[0]);
return '';
}
if (!this.specificHandler.isMarkedAsSelected(this.indexedXPath) &&
!this.specificHandler.isInFormData(this.indexedXPath)) {
return '';
}
var selectionInfo = this.specificHandler.getSelectionInfo(this.indexedXPath);
var id = this.indexedXPath + '_mode';
$(id).value = selectionInfo.mode;
this.simulateAction($(id), 'change');
if (selectionInfo.mode == this.MODE_CUSTOM_VALUE) {
id = this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE;
$(id).value = selectionInfo['custom_value'];
this.simulateAction($(id), 'change');
}
if (selectionInfo.mode == this.MODE_CUSTOM_ATTRIBUTE) {
id = this.indexedXPath +'_'+ this.MODE_CUSTOM_ATTRIBUTE;
$(id).value = selectionInfo['custom_attribute'];
this.simulateAction($(id), 'change');
}
if (selectionInfo.mode == this.MODE_RECOMMENDED_VALUE) {
id = this.indexedXPath +'_'+ this.MODE_RECOMMENDED_VALUE;
$(id).value = selectionInfo['recommended_value'];
this.simulateAction($(id), 'change');
}
},
forceSelectAndDisable: function(value)
{
if (!value) {
return;
}
var modeSelect = $(this.indexedXPath + '_mode');
modeSelect.value = this.MODE_CUSTOM_VALUE;
this.simulateAction(modeSelect, 'change');
modeSelect.setAttribute('disabled','disabled');
var valueObj = $(this.indexedXPath +'_'+ this.MODE_CUSTOM_VALUE);
valueObj.value = value;
this.simulateAction(valueObj, 'change');
valueObj.setAttribute('disabled', 'disabled');
},
//########################################
getToolTipBlock: function(id, messageHtml)
{
var container = new Element('div', {
'id' : id,
'style': 'float: right; display: none;'
});
container.appendChild(new Element('img', {
'src' : M2ePro.url.get('m2epro_skin_url') + '/images/tool-tip-icon.png',
'class' : 'tool-tip-image'
}));
var htmlCont = container.appendChild(new Element('span', {
'class' : 'tool-tip-message tip-left',
'style' : 'display: none; max-width: 500px;'
}));
htmlCont.appendChild(new Element('img', {
'src': M2ePro.url.get('m2epro_skin_url') + '/images/help.png'
}));
htmlCont.appendChild(new Element('span')).insert(messageHtml);
return container;
},
// ---------------------------------------
getCustomValueTypeNote: function()
{
if (this.specific.data_definition.definition) {
return null;
}
if (this.specific.params.type == 'int') return this.getIntTypeNote(this.specific.params);
if (this.specific.params.type == 'float') return this.getFloatTypeNote(this.specific.params);
if (this.specific.params.type == 'string') return this.getStringTypeNote(this.specific.params);
if (this.specific.params.type == 'date_time') return this.getDatTimeTypeNote(this.specific.params);
return this.getAnyTypeNote(this.specific.params);
},
getIntTypeNote: function(params)
{
var notes = [];
var handler = {
'type': function() {
notes[0] = M2ePro.translator.translate('Type: Numeric.') + ' ';
},
'min_value': function(restriction) {
notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. ';
},
'max_value': function(restriction) {
notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. ';
},
'total_digits': function(restriction) {
notes[3] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. ';
}
};
for (var paramName in params) {
params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]);
}
return notes.join('');
},
getFloatTypeNote: function(params)
{
var notes = [];
var handler = {
'type': function() {
notes[0] = M2ePro.translator.translate('Type: Numeric floating point.') + ' ';
},
'min_value': function(restriction) {
notes[1] = M2ePro.translator.translate('Min:') + ' ' + restriction + '. ';
},
'max_value': function(restriction) {
notes[2] = M2ePro.translator.translate('Max:') + ' ' + restriction + '. ';
},
'decimal_places': function(restriction) {
notes[3] = M2ePro.translator.translate('Decimal places (not more):') + ' ' + restriction.value + '. ';
},
'total_digits': function(restriction) {
notes[4] = M2ePro.translator.translate('Total digits (not more):') + ' ' + restriction + '. ';
}
};
for (var paramName in params) {
params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]);
}
return notes.join('');
},
getStringTypeNote: function(params)
{
var notes = [];
var handler = {
'type': function() {
notes[0] = M2ePro.translator.translate('Type: String.') + ' ';
},
'min_length': function(restriction) {
notes[1] = restriction != 1 ? M2ePro.translator.translate('Min length:') + ' ' + restriction : '';
},
'max_length': function(restriction) {
notes[2] = M2ePro.translator.translate('Max length:') + ' ' + restriction;
},
'pattern': function(restriction) {
if (restriction == '[a-zA-Z][a-zA-Z]|unknown') {
notes[3] = M2ePro.translator.translate('Two uppercase letters or "unknown".');
}
}
};
for (var paramName in params) {
params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]);
}
return notes.join('');
},
getDatTimeTypeNote: function(params)
{
var notes = [];
var handler = {
'type': function(restriction) {
notes.push(M2ePro.translator.translate('Type: Date time. Format: YYYY-MM-DD hh:mm:ss'));
}
};
for (var paramName in params) {
params.hasOwnProperty(paramName) && handler[paramName] && handler[paramName](params[paramName]);
}
return notes.join('');
},
getAnyTypeNote: function(params)
{
return M2ePro.translator.translate('Can take any value.');
},
// ---------------------------------------
getCustomAttributeTypeNote: function()
{
if (this.specific.values.length <= 0 && this.specific.recommended_values.length <= 0) {
return null;
}
var span = new Element('span');
var title = this.specific.values.length > 0 ? M2ePro.translator.translate('Allowed Values') : M2ePro.translator.translate('Recommended Values');
span.appendChild(new Element('span')).insert('<b>' + title + ': </b>');
var ul = span.appendChild(new Element('ul'));
var noteValues = this.specific.values.length > 0 ? this.specific.values : this.specific.recommended_values;
noteValues.each(function(value) {
ul.appendChild(new Element('li')).insert(value);
});
return span.outerHTML;
},
// ---------------------------------------
getDefinitionNote: function(definitionPart)
{
if (!definitionPart.definition) {
return;
}
var div = new Element('div');
div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'}))
.insert('<b>' + M2ePro.translator.translate('Definition:') + '</b>');
div.appendChild(new Element('div'))
.insert(definitionPart.definition);
if (definitionPart.tips && definitionPart.tips.match(/[a-z0-9]/i)) {
div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'}))
.insert('<b>' + M2ePro.translator.translate('Tips:') + '</b>');
div.appendChild(new Element('div'))
.insert(definitionPart.tips);
}
if (definitionPart.example && definitionPart.example.match(/[a-z0-9]/i)) {
div.appendChild(new Element('div', {style: 'padding: 2px 0; margin-top: 5px;'}))
.insert('<b>' + M2ePro.translator.translate('Examples:') + '</b>');
div.appendChild(new Element('div'))
.insert(definitionPart.example);
}
return div.outerHTML;
},
// ---------------------------------------
getSpecificOverriddenNotice: function()
{
if (!this.specificHandler.canSpecificBeOverwrittenByVariationTheme(this.specific)) {
return null;
}
var variationThemesList = this.specificHandler.themeAttributes[this.specific.xml_tag];
var message = '<b>' + M2ePro.translator.translate('Value of this Specific can be automatically overwritten by M2E Pro.') + '</b>';
message += '<br/><br/>' + variationThemesList.join(', ');
return this.constructNotice(message);
},
getSpecificParentageNotice: function()
{
if (this.specific.xml_tag != 'Parentage') {
return null;
}
return this.constructNotice(M2ePro.translator.translate('Amazon Parentage Specific will be overridden notice.'));
},
constructNotice: function(message)
{
var container = new Element('div', {
'style': 'float: right; margin-right: 3px; margin-top: 1px;'
});
container.appendChild(new Element('img', {
'src' : M2ePro.url.get('m2epro_skin_url') + '/images/warning.png',
'class' : 'tool-tip-image'
}));
var htmlCont = container.appendChild(new Element('span', {
'class' : 'tool-tip-message tip-left',
'style' : 'display: none; max-width: 500px; border-color: #ffd967; background-color: #fffbf0;'
}));
htmlCont.appendChild(new Element('img', {
'src' : M2ePro.url.get('m2epro_skin_url') + '/images/i_notice.gif',
'style' : 'margin-top: -21px;'
}));
htmlCont.appendChild(new Element('span')).insert(message);
return container;
},
//########################################
observeToolTips: function(indexedXpath)
{
$$('tr[id="' + indexedXpath + '"] .tool-tip-image').each(function(element) {
element.observe('mouseover', MagentoFieldTipObj.showToolTip);
element.observe('mouseout', MagentoFieldTipObj.onToolTipIconMouseLeave);
});
$$('tr[id="' + indexedXpath + '"] .tool-tip-message').each(function(element) {
element.observe('mouseout', MagentoFieldTipObj.onToolTipMouseLeave);
element.observe('mouseover', MagentoFieldTipObj.onToolTipMouseEnter);
});
},
//########################################
removeAction: function($super, event)
{
// for attributes removing
var myEvent = new CustomEvent('parent-specific-row-is-removed');
$(this.indexedXPath).dispatchEvent(myEvent);
// ---------------------------------------
var deleteResult = $super(event);
this.throwEventsToParents();
return deleteResult;
},
cloneAction: function($super, event)
{
var newIndexedXpath = $super(event);
this.observeToolTips(newIndexedXpath);
var myEvent = new CustomEvent('parent-specific-row-is-cloned', { 'new_indexed_xpath': newIndexedXpath });
$(this.indexedXPath).dispatchEvent(myEvent);
return newIndexedXpath;
},
// ---------------------------------------
getRowContainer: function()
{
if ($(this.indexedXPath)) {
return $(this.indexedXPath);
}
var grid = $$('table[id="'+ this.getParentIndexedXpath() +'_grid"] table.border tbody').first();
return grid.appendChild(new Element('tr', {id: this.indexedXPath}));
}
// ---------------------------------------
}); | portchris/NaturalRemedyCompany | src/js/M2ePro/Amazon/Template/Description/Category/Specific/Grid/RowRenderer.js | JavaScript | mit | 28,752 |
Rails.application.config.middleware.use OmniAuth::Builder do
provider :provider, ENV["KEY"], ENV["SECRET"]
end
| mariochavez/mac_generators | lib/generators/authentication/omniauth/templates/omniauth.rb | Ruby | mit | 113 |
package controller.server;
import controller.LibraryService;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.rmi.RemoteException;
public class RMIServer {
public static void main(String[] args) throws RemoteException, NamingException {
LibraryService service = new DBController();
Context namingContext = new InitialContext();
namingContext.rebind("rmi:books", service);
System.out.println("RMI-server is working...");
}
}
| niralittle/LibraryApp | src/controller/server/RMIServer.java | Java | mit | 533 |
define([
'angular'
], function (ng) {
'use strict';
return ng.module('backgroundModule', []);
});
| lukasz-si/resume | app/components/background-code/module.js | JavaScript | mit | 112 |
const pkg = state => state.pkg
const app = state => state.app
const device = state => state.app.device
const sidebar = state => state.app.sidebar
const effect = state => state.app.effect
const menuitems = state => state.menu.items
const componententry = state => {
return state.menu.item.filter(c => c.meta && c.meta.label === 'Components')[0]
}
export {
pkg,
app,
device,
sidebar,
effect,
menuitems,
componententry
}
| blushft/wespk | client/src/store/getters.js | JavaScript | mit | 435 |
title: HOWTO: Install Ubuntu on Your Eee PC
author: Rami Taibah
permalink: howto-install-ubuntu-on-your-eee-pc
tags: eee-pc, ubuntu, howto
I have [posted]({filename}/blog/2008-02-06-eee-pcfinally.markdown) earlier that the "easy mode" of the Eee PC is like living on the bottom bunker in a basement cell of the Alcatraz. Liberating it to the default Xandros "advanced mode" is just like going out to yard with sweaty inmates, which isn't saying much.
I initially installed eeexubuntu on that little critter, but soon was disenchanted. XFCE is just not for me. Solution? Install everybody's favorite! Ubuntu!
## USB disk or CD drive?
Installing a different distro on your Eee PC is done either by using a USB thumb drive or an external CD drive. I expect that the Eee PC is the first Linux experience to a lot of Eee PC users, so I would recommend getting an external CD drive, it's much less of a hassle.
## Downloading, burning, and preperation
First of all you will need to get Ubuntu. At the time of writing this, Ubuntu 7.10 (Gutsy) is the latest so get it either through direct [download](http://www.ubuntu.com/getubuntu/download) or [torrent](http://torrent.ubuntu.com:6969/file?info\_hash=%ED%8A%B7%FB%3AL%D3Nd%8EH%A4%0F%8F%DD%97%A4%F5%40%D2).
Then you will need to burn it on a CD using your favorite image burner. (there are many guides for that, google it)
You will also probably need to edit the boot sequence in your bios. So restart your Eee PC and press F2 to enter the bios menu and change the primary boot to "USB Optical Drive". Pop in the Ubuntu CD in your external drive and restart. Then press enter when you get the list of options (first option).
A couple of minutes later you will be on your default Ubuntu desktop. Before clicking the "install" icon, you will need to disable the desktop effects. Since the installer doesn't fit into the small Eee PC screen, you will need to use the ALT+Right click option to move the installer window. So System --> Prefrences --> Appearence and then go to the last tab "Visual Effects" and then select none.
## Installation
Now you are ready for installing, so click on the "Install" icon located on your desktop (pictures are eclipsed due to screen size):

Select your language.

Select your keyboard layout.

Select manual partitioning.

This is the tricky part, basically you will need to set a root partition for the system to be installed in. So we are going to partition /dev/sda1 and make it our root. Click on /dev/sda1 and then delete whatever partitions under it. Then click on new and in filesystem choose ext2 (we are not going to use ext3 because we want to limit writes due to the solid state disk nature of the Eee PC). Also set mount point to "/" (without the quotes).
If you have an SDHC card click on it and edit the mount point to "/media/\*whatever\*". If you have nothing interesting in that card you might want to just delete whatever partitions and make a new partition, and choosing the filesystem as "fat32″. Since you never know when you might want to use it on Windows machine ;).

Enter your details. Name, user name, password, and machine name. Click next.
You will be prompted with a warning that all your data will be wiped out, click OK. Now sit back and relax, your system will be ready in 30 minutes or so.
Thats it! Now just click restart system when prompted, you will then asked to eject CD.
Now your golden :)
A lot of functionality will be missing with this out of the box Ubuntu installation. For example your wireless won't function. Visit my [Perfect Eee PC Ubuntu Installation Guide]({filename}/blog/2008-02-21-howto-your-perfect-ubuntu-on-your-perfect-eee-pc.markdown) for a complete guide on how to get things up and running.
| rtaibah/pelican-blog | content/blog/2008-02-11-howto-install-ubuntu-on-your-eee-pc.markdown | Markdown | mit | 4,126 |
using System;
using System.Collections.Generic;
using System.Linq;
using BlackBox.Service;
using EbInstanceModel;
using IFC2X3;
namespace BlackBox.Predefined
{
public partial class BbProduct : BbBase
{
[EarlyBindingInstance]
public virtual IfcRelAggregates IfcRelAggregates { get; protected set; }
public BbLocalPlacement3D ObjectBbLocalPlacement { get; protected set; }
public virtual IfcObject IfcObject { get; protected set; }
public string Name
{
get { return IfcObject.Name; }
protected set { IfcObject.Name = value; }
}
public string Description
{
get { return IfcObject.Description; }
protected set { IfcObject.Description = value; }
}
public string ObjectType
{
get { return IfcObject.ObjectType; }
protected set { IfcObject.ObjectType = value; }
}
[EarlyBindingInstanceCollection]
public BbProduct HostObject { get; protected set; }
protected BbProduct()
: this(Guid.NewGuid())
{
}
protected BbProduct(Guid guid)
: base(guid)
{
}
public void AddToHostObject(BbProduct hostObject)
{
HostObject = hostObject;
var a = EarlyBindingInstanceModel.GetReferencedEntities(hostObject.IfcObject.EIN).Values;
var b = (from x in a.OfType<IfcRelAggregates>()
where x.RelatingObject.EIN == hostObject.IfcObject.EIN
select x).ToList();
switch (b.Count)
{
case 0:
IfcRelAggregates = new IfcRelAggregates
{
GlobalId = IfcGloballyUniqueId.NewGuid(),
OwnerHistory = hostObject.IfcObject.OwnerHistory,
RelatingObject = hostObject.IfcObject,
RelatedObjects = new List<IfcObjectDefinition>() { },
};
break;
case 1:
IfcRelAggregates = b[0];
break;
default:
throw new NotImplementedException();
}
var aa = GetType().GetProperty("IfcObject").GetValue(this, null) as IfcObject;
IfcRelAggregates.RelatedObjects.Add(aa);
}
}
}
| donghoon/ifctoolkit | BlackBox/Predefined/BbProduct/BbProduct.cs | C# | mit | 2,469 |
##################################################
"""
symbols(name(s), assumptions...)
Calls `sympy.symbols` to produce symbolic variables and symbolic functions. An alternate to the recommended `@syms`, (when applicable)
In sympy `sympy.symbols` and `sympy.Symbol` both allow the construction of symbolic variables and functions. The `Julia` function `symbols` is an alias for `sympy.symbols`.
* Variables are created through `x=symbols("x")`;
* Assumptions on variables by `x=symbols("x", real=true)`;
* Multiple symbols `x1,x2 = symbols("x[1:3]")` can be created. Unlike `@syms`, the number of variables can be specified with a variable through interpolation.
* Symbolic functions can be created py passing `cls=sympy.Function`, `symbols("F", cls=sympy.Function, real=true)`
"""
function symbols(x::AbstractString; kwargs...)
out = sympy.symbols(x; kwargs...)
end
symbols(x::Symbol; kwargs...) = symbols(string(x); kwargs...)
symbols(xs::T...; kwargs...) where {T <: SymbolicObject} = xs
"""
@vars x y z
Define symbolic values, possibly with names and assumptions
Examples:
```
@vars x y
@vars a1=>"α₁"
@vars a b real=true
```
!!! Note:
The `@syms` macro is recommended as it has a more flexible syntax
"""
macro vars(x...)
q = Expr(:block)
as = [] # running list of assumptions to be applied
ss = [] # running list of symbols created
for s in reverse(x)
if isa(s, Expr) # either an assumption or a named variable
if s.head == :(=)
s.head = :kw
push!(as, s)
elseif s.head == :call && s.args[1] == :(=>)
push!(ss, s.args[2])
push!(q.args, Expr(:(=), esc(s.args[2]), Expr(:call, :symbols, s.args[3], map(esc,as)...)))
end
elseif isa(s, Symbol) # raw symbol to be created
push!(ss, s)
push!(q.args, Expr(:(=), esc(s), Expr(:call, :symbols, Expr(:quote, s), map(esc,as)...)))
else
throw(AssertionError("@vars expected a list of symbols and assumptions"))
end
end
push!(q.args, Expr(:tuple, map(esc,reverse(ss))...)) # return all of the symbols we created
q
end
"""
@syms a n::integer x::(real,positive)=>"x₀" y[-1:1] u() v()::real w()::(real,positive) y()[1:3]::real
Construct symbolic variables or functions along with specified assumptions. Similar to `@vars`, `sympy.symbols`, and `sympy.Function`, but the specification of the assumptions is more immediate than those interfaces which follow sympy's constructors.
Allows the specification of assumptions on the variables and functions.
* a type-like annontation, such as `n::integer` is equivalent to `sympy.symbols("n", integer=true)`. Multiple assumptions are combined using parentheses (e.g., `n::(integer,nonnegative)`.
The possible [values](https://docs.sympy.org/latest/modules/core.html#module-sympy.core.assumptions) for assumptions are: "commutative", "complex", "imaginary", "real", "integer", "odd", "even", "prime", "composite", "zero", "nonzero", "rational", "algebraic", "transcendental", "irrational", "finite", "infinite", "negative", "nonnegative", "positive", "nonpositive", "hermitian", "antihermetian".
* a tensor declaration form is provided to define arrays of variables, e.g. `x[-1:1]` or `y[1:4, 2:5]`.
* a symbolic function can be specified using a pair of parentheses after the name, as in `u()`.
* The return type of a function can have assumptions specified, as with a variable. E.g., `h()::complex`. How the symbolic function prints can be set as with a variable, e.g. `h()::complex=>"h̄"`.
* multiple definitions can be separated by commas
* How the symbol prints (the `__str__()` value) can be specified using the syntax `=>"name"`, as in `x=>"xₒ"`
## Examples:
```jldoctest constructors
julia> using SymPy
julia> @syms a b::nonnegative
(a, b)
julia> sqrt(a^2), sqrt(b^2)
(sqrt(a^2), b)
```
```jldoctest constructors
julia> @syms x::prime
(x,)
julia> ask(𝑄.negative(x)), ask(𝑄.integer(x)), ask(𝑄.even(x)) # (false, true, nothing)
(false, true, nothing)
```
```jldoctest constructors
julia> @syms a[0:5], x
(Sym[a₀, a₁, a₂, a₃, a₄, a₅], x)
julia> sum( aᵢ*x^(i) for (i,aᵢ) ∈ zip(0:5, a)) |> print
a₀ + a₁*x + a₂*x^2 + a₃*x^3 + a₄*x^4 + a₅*x^5
```
```jldoctest constructors
julia> @syms x u() v()::nonnegative
(x, u, v)
julia> sqrt(u(x)^2), sqrt(v(x)^2) # sqrt(u(x)^2), Abs(v(x))
(sqrt(u(x)^2), Abs(v(x)))
```
!!! Note:
Many thanks to `@matthieubulte` for this contribution.
"""
macro syms(xs...)
# If the user separates declaration with commas, the top-level expression is a tuple
if length(xs) == 1 && isa(xs[1], Expr) && xs[1].head == :tuple
_gensyms(xs[1].args...)
elseif length(xs) > 0
_gensyms(xs...)
end
end
function _gensyms(xs...)
asstokw(a) = Expr(:kw, esc(a), true)
# Each declaration is parsed and generates a declaration using `symbols`
symdefs = map(xs) do expr
decl = parsedecl(expr)
symname = sym(decl)
symname, gendecl(decl)
end
syms, defs = collect(zip(symdefs...))
# The macro returns a tuple of Symbols that were declared
Expr(:block, defs..., :(tuple($(map(esc,syms)...))))
end
## avoid PyObject conversion as possible
Sym(x::T) where {T <: Number} = sympify(x)
Sym(x::Rational{T}) where {T} = Sym(numerator(x))/Sym(denominator(x))
function Sym(x::Complex{Bool})
!x.re && x.im && return IM
!x.re && !x.im && return zero(Sym)
x.re && !x.im && return Sym(1)
x.re && x.im && return Sym(1) + IM
end
Sym(x::Complex{T}) where {T} = Sym(real(x)) + Sym(imag(x)) * IM
Sym(xs::Symbol...) = Tuple(Sym.((string(x) for x in xs)))
Sym(x::AbstractString) = sympy.symbols(x)
Sym(s::SymbolicObject) = s
Sym(x::Irrational{T}) where {T} = convert(Sym, x)
convert(::Type{Sym}, s::AbstractString) = Sym(s)
sympify(s, args...; kwargs...) = pycall(sympy.sympify::PyCall.PyObject, Sym, s) #sympy.sympify(s, args...; kwargs...)
SymMatrix(s::SymMatrix) = s
SymMatrix(s::Sym) = sympy.ImmutableMatrix([s])
SymMatrix(A::Matrix) = sympy.ImmutableMatrix([A[i,:] for i in 1:size(A)[1]])
| JuliaPy/SymPy.jl | src/constructors.jl | Julia | mit | 6,177 |
using UnityEngine;
public class Crouch : MonoBehaviour {
public float crouchColliderProportion = 0.75f;
private bool crouching;
private float colliderCenterY, centerOffsetY;
private ChipmunkBoxShape box;
private Jump jump;
private Sneak sneak;
private WalkAbs move;
private AnimateTiledConfig crouchAC;
void Awake () {
crouching = false;
// take the collider and some useful values
box = GetComponent<ChipmunkBoxShape>();
colliderCenterY = box.center.y;
centerOffsetY = ((1f - crouchColliderProportion)*0.5f) * box.size.y;
jump = GetComponent<Jump>();
sneak = GetComponent<Sneak>();
move = GetComponent<WalkAbs>();
crouchAC = AnimateTiledConfig.getByName(gameObject, EnumAnimateTiledName.Crouch, true);
}
// Update is called once per frame
public void crouch () {
// is it jumping?
bool jumping = false;
if (jump != null && jump.isJumping())
jumping = true;
// is it moving?
bool moving = false;
if (move != null && move.isWalking())
moving = true;
// if crouching then update accordingly
if (sneak != null && crouching) {
// while in the air we can't sneak
if (jumping) {
if (sneak.isSneaking()) {
sneak.stopSneaking();
crouchAC.setupAndPlay();
}
}
// if not jumping and not moving and sneaking: stop sneaking and do crouch
else if (!moving) {
if (sneak.isSneaking()) {
sneak.stopSneaking();
crouchAC.setupAndPlay();
}
}
// if not jumping and moving: sneak
else
sneak.sneak();
}
// don't update
if (crouching || jumping)
return;
crouching = true;
// resize the collider
Vector3 theSize = box.size;
theSize.y *= crouchColliderProportion;
box.size = theSize;
// transform the collider
Vector3 theCenter = box.center;
theCenter.y -= centerOffsetY;
box.center = theCenter;
// set the correct sprite animation
crouchAC.setupAndPlay();
}
public void noCrouch () {
if (sneak != null)
sneak.stopSneaking();
if (!crouching)
return;
move.stop(); // this force the reset of the sprite animation
crouchAC.stop();
crouching = false;
// transform the collider
Vector3 theCenter = box.center;
theCenter.y = colliderCenterY;
box.center = theCenter;
// resize the collider
Vector3 theSize = box.size;
theSize.y /= crouchColliderProportion;
box.size = theSize;
}
public bool isCrouching () {
return crouching;
}
}
| fabri1983/marioBadClone | Assets/Scripts/States/Crouch.cs | C# | mit | 2,429 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Plato - lib/cmds/nt.js</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link href="../../assets/css/vendor/morris.css" rel="stylesheet">
<link href="../../assets/css/vendor/bootstrap.css" rel="stylesheet">
<link href="../../assets/css/vendor/font-awesome.css" rel="stylesheet">
<link href="../../assets/css/vendor/codemirror.css" rel="stylesheet">
<link href="../../assets/css/plato.css" rel="stylesheet">
<link href="../../assets/css/plato-file.css" rel="stylesheet">
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="container">
<a class="navbar-brand" href="http://github.com/es-analysis/plato">Plato on Github</a>
<ul class="nav navbar-nav">
<li>
<a href="../../index.html">Report Home</a>
</li>
</ul>
</div>
</div>
<div class="jumbotron">
<div class="container">
<h1>lib/cmds/nt.js</h1>
</div>
</div>
<div class="container aggregate-stats">
<div class="row">
<div class="col-md-6">
<h2 class="header">Maintainability <a href="http://blogs.msdn.com/b/codeanalysis/archive/2007/11/20/maintainability-index-range-and-meaning.aspx"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="A value between 0 and 100 that represents the relative ease of maintaining the code. A high value means better maintainability." data-original-title="Maintainability Index" data-container="body"></i></a></h2>
<p class="stat">64.69</p>
</div>
<div class="col-md-6">
<h2 class="header">Lines of code <i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="Source Lines of Code / Logical Lines of Code" data-original-title="SLOC/LSLOC" data-container="body"></i></h2>
<p class="stat">179</p>
</div>
</div>
<div class="row historical">
<div class="col-md-6">
<p id="chart_historical_maint" class="chart"></p>
</div>
<div class="col-md-6">
<p id="chart_historical_sloc" class="chart"></p>
</div>
</div>
<div class="row">
<div class="col-md-6">
<h2 class="header">Difficulty <a href="http://en.wikipedia.org/wiki/Halstead_complexity_measures"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="The difficulty measure is related to the difficulty of the program to write or understand." data-original-title="Difficulty" data-container="body"></i></a></h2>
<p class="stat">21.07</p>
</div>
<div class="col-md-6">
<h2 class="header">Estimated Errors <a href="http://en.wikipedia.org/wiki/Halstead_complexity_measures"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="Halstead's delivered bugs is an estimate for the number of errors in the implementation." data-original-title="Delivered Bugs" data-container="body"></i></a></h2>
<p class="stat">1.21</p>
</div>
</div>
</div>
<div class="container charts">
<div class="row">
<h2 class="header">Function weight</h2>
</div>
<div class="row">
<div class="col-md-6">
<h3 class="chart-header">By Complexity <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity"><i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="This metric counts the number of distinct paths through a block of code. Lower values are better." data-original-title="Cyclomatic Complexity" data-container="body"></i></a></h3>
<div id="fn-by-complexity" class="stat"></div>
</div>
<div class="col-md-6">
<h3 class="chart-header">By SLOC <i class="icon icon-info-sign" rel="popover" data-placement="top" data-trigger="hover" data-content="Source Lines of Code / Logical Lines of Code" data-original-title="SLOC/LSLOC" data-container="body"></i></h3>
<div id="fn-by-sloc" class="stat"></div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<textarea id="file-source" class="col-md-12">/*
* Copyright 2013 Zeno Rocha, All Rights Reserved.
*
* Code licensed under the BSD License:
* https://github.com/eduardolundgren/blob/master/LICENSE.md
*
* @author Zeno Rocha <[email protected]>
*/
// -- Requires -----------------------------------------------------------------
var async = require('async'),
base = require('../base'),
clc = require('cli-color'),
logger = require('../logger'),
printed = {};
// -- Constructor --------------------------------------------------------------
function Notifications(options) {
this.options = options;
if (!options.repo) {
logger.error('You must specify a Git repository to run this command');
}
}
// -- Constants ----------------------------------------------------------------
Notifications.DETAILS = {
options: {
'latest': Boolean,
'repo' : String,
'user' : String,
'watch' : Boolean
},
shorthands: {
'l': [ '--latest' ],
'r': [ '--repo' ],
'u': [ '--user' ],
'w': [ '--watch' ]
},
description: 'Provides a set of util commands to work with Notifications.'
};
// -- Commands -----------------------------------------------------------------
Notifications.prototype.run = function() {
var instance = this,
options = instance.options;
if (options.latest) {
logger.logTemplate('{{prefix}} [info] Listing activities on {{greenBright options.user "/" options.repo}}', {
options: options
});
instance.latest();
}
if (options.watch) {
logger.logTemplate('{{prefix}} [info] Watching any activity on {{greenBright options.user "/" options.repo}}', {
options: options
});
instance.watch();
}
};
Notifications.prototype.latest = function(opt_watch) {
var instance = this,
options = instance.options,
operations,
payload,
listEvents,
filteredListEvents = [];
operations = [
function(callback) {
payload = {
user: options.user,
repo: options.repo
};
base.github.events.getFromRepo(payload, function(err, data) {
if (!err) {
listEvents = data;
}
callback(err);
});
},
function(callback) {
listEvents.forEach(function(event) {
event.txt = instance.getMessage_(event);
if (options.watch) {
if (!printed[event.created_at]) {
filteredListEvents.push(event);
}
}
else {
filteredListEvents.push(event);
}
printed[event.created_at] = true;
});
callback();
}
];
async.series(operations, function(err) {
if (filteredListEvents.length) {
logger.logTemplateFile('nt.handlebars', {
user: options.user,
repo: options.repo,
latest: options.latest,
watch: opt_watch,
events: filteredListEvents
});
}
logger.defaultCallback(err, null, false);
});
};
Notifications.prototype.watch = function() {
var instance = this,
intervalTime = 3000;
instance.latest();
setInterval(function() {
instance.latest(true);
}, intervalTime);
};
Notifications.prototype.getMessage_ = function(event) {
var instance = this,
txt = '',
type = event.type,
payload = event.payload;
switch (type) {
case 'CommitCommentEvent':
txt = 'commented on a commit at';
break;
case 'CreateEvent':
txt = 'created a ' + payload.ref_type + ' at';
break;
case 'DeleteEvent':
txt = 'removed ' + payload.ref_type + ' at';
break;
case 'DownloadEvent':
txt = 'downloaded';
break;
case 'ForkEvent':
txt = 'forked';
break;
case 'ForkApplyEvent':
txt = 'applied patch ' + payload.head + ' at';
break;
case 'IssueCommentEvent':
txt = 'commented on an issue at';
break;
case 'IssuesEvent':
txt = payload.action + ' an issue at';
break;
case 'MemberEvent':
txt = 'added ' + payload.member + ' as a collaborator to';
break;
case 'PublicEvent':
txt = 'open sourced';
break;
case 'PullRequestEvent':
txt = payload.action + ' pull request #' + payload.number + ' at';
break;
case 'PullRequestReviewCommentEvent':
txt = 'commented on a pull request at';
break;
case 'PushEvent':
txt = 'pushed ' + payload.commits.length + ' commit(s) to';
break;
case 'WatchEvent':
txt = 'is now watching';
break;
default:
logger.error('event type not found: ' + clc.red(type));
break;
}
return txt;
};
exports.Impl = Notifications;</textarea>
</div>
</div>
<footer class="footer">
<div class="container">
<p>.</p>
</div>
</footer>
<script type="text/html" id="complexity-popover-template">
<div class="complexity-notice">
Complexity : {{ complexity.cyclomatic }} <br>
Length : {{ complexity.halstead.length }} <br>
Difficulty : {{ complexity.halstead.difficulty.toFixed(2) }} <br>
Est # bugs : {{ complexity.halstead.bugs.toFixed(2) }}<br>
</div>
</script>
<script type="text/javascript" src="../../assets/scripts/bundles/core-bundle.js"></script>
<script type="text/javascript" src="../../assets/scripts/bundles/codemirror.js"></script>
<script type="text/javascript" src="../../assets/scripts/codemirror.markpopovertext.js"></script>
<script type="text/javascript" src="report.js"></script>
<script type="text/javascript" src="report.history.js"></script>
<script type="text/javascript" src="../../assets/scripts/plato-file.js"></script>
</body>
</html>
| node-gh/reports | complexity/files/lib_cmds_nt_js/index.html | HTML | mit | 11,120 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.applicationinsights.models;
import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.UUID;
/** User assigned identity properties. */
@Immutable
public class UserAssignedIdentity {
@JsonIgnore private final ClientLogger logger = new ClientLogger(UserAssignedIdentity.class);
/*
* The principal ID of the assigned identity.
*/
@JsonProperty(value = "principalId", access = JsonProperty.Access.WRITE_ONLY)
private UUID principalId;
/*
* The client ID of the assigned identity.
*/
@JsonProperty(value = "clientId", access = JsonProperty.Access.WRITE_ONLY)
private UUID clientId;
/**
* Get the principalId property: The principal ID of the assigned identity.
*
* @return the principalId value.
*/
public UUID principalId() {
return this.principalId;
}
/**
* Get the clientId property: The client ID of the assigned identity.
*
* @return the clientId value.
*/
public UUID clientId() {
return this.clientId;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| Azure/azure-sdk-for-java | sdk/applicationinsights/azure-resourcemanager-applicationinsights/src/main/java/com/azure/resourcemanager/applicationinsights/models/UserAssignedIdentity.java | Java | mit | 1,557 |
__precompile__(true)
module ImplicitEquations
using ValidatedNumerics
import ValidatedNumerics: Interval, diam
using RecipesBase
using Compat
include("predicates.jl")
include("intervals.jl")
include("tupper.jl")
include("asciigraphs.jl")
#include("plot.jl")
include("plot_recipe.jl")
export eq, neq, ⩵, ≷, ≶
export screen, I_
export asciigraph
#export GRAPH, OInterval
#export Region, compute, negate_op
#export TRUE, FALSE, MAYBE
end # module
| JuliaPackageMirrors/ImplicitEquations.jl | src/ImplicitEquations.jl | Julia | mit | 461 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
angular.module('MetronicApp').controller('UsuariosCtrl', function ($scope, GetSv, $rootScope, PostSv,toaster) {
$scope.usuarios = [];
$scope.add = false;
$scope.edit = false;
$scope.a_editar = {};
$scope.usuario = {};
$scope.getUsers = function () {
GetSv.getData("usuarios").then(function (data) {
if (data.Error) {
$scope.error = true;
} else {
$scope.usuarios = data;
$scope.error = false;
}
}, function (e) {
$scope.error = true;
});
};
$scope.getUsers();
$scope.closeEdit = function () {
$scope.a_editar = {};
$scope.edit = false;
};
$scope.openEdit = function (item) {
$scope.a_editar = item;
$scope.edit = true;
};
$scope.closeAdd = function () {
$scope.add = false;
};
$scope.openAdd = function (item) {
$scope.a_editar = {};
$scope.add = true;
};
$scope.sendUser = function (servlet, user) {
PostSv.postData(servlet, {usuario: JSON.stringify(user)}).then(function (data) {
if (data.Error) {
toaster.pop('error', "Error", data.Error);
} else {
toaster.pop('success', "Exito", data.Exito);
$scope.a_editar = {};
$scope.usuario = {};
$scope.getUsers();
$scope.add = false;
$scope.edit = false;
}
}, function (e) {
toaster.pop('error', "Error", "Error fatal");
}
);
};
$scope.roles = $rootScope.roles;
});
| JoPaRoRo/Fleet | web/js/controllers/usuarios.js | JavaScript | mit | 1,854 |
#include <vector>
#include <memory>
#include <iostream>
using namespace std;
shared_ptr<vector<int>> make() {
return make_shared<vector<int>>();
}
shared_ptr<vector<int>> read(shared_ptr<vector<int>> p) {
cout << "Enter values: " << endl;
int x;
while (cin >> x) {
p->push_back(x);
}
return p;
}
void print(shared_ptr<vector<int>> p) {
for (int i : *p) {
cout << i << " ";
}
}
int main() {
auto p = read(make());
print(p);
return 0;
} | mcshen99/learningCpp | learningCpp/primer12_7.cpp | C++ | mit | 458 |
/*
* This file exports the configuration Express.js back to the application
* so that it can be used in other parts of the product.
*/
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
exports.setup = function(app, express) {
app.set('views', path.join(__dirname + '../../public/views'));
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
cookie: { maxAge: (24*3600*1000*30) },
store: new RedisStore({
host: 'localhost',
port: 6379,
db: 1,
pass: ''
}),
secret: 'mylittlesecret',
resave: false,
saveUninitialized: false
}));
app.use(express.static(path.join(__dirname + '../../public')));
} | kurtbradd/facebook-music-recommender | config/express-config.js | JavaScript | mit | 1,002 |
---
layout: pattern
summary: "Base classes for creating simple 'nav-like' lists. Ideal for simple nav menus or for forming the basis of more complex navigation componenets."
---
<ul class="tan-nav-menu tan-nav-menu--stacked">
{% for i in (1..4) %}
<li class="">
<a href="#">Stacked Link {{i}}</a>
</li>
{% endfor %}
</ul>
<br><br><br>
<ul class="tan-nav-menu tan-nav-menu--inline">
{% for i in (1..4) %}
<li class="">
<a href="#">Inline Link {{i}}</a>
</li>
{% endfor %}
</ul>
| getdave/tanlinell-framework | docs/src/_compounds/nav-menu.html | HTML | mit | 500 |
(function() {
chai.should();
describe("Dropzone", function() {
var getMockFile, xhr;
getMockFile = function() {
return {
status: Dropzone.ADDED,
accepted: true,
name: "test file name",
size: 123456,
type: "text/html"
};
};
xhr = null;
beforeEach(function() {
return xhr = sinon.useFakeXMLHttpRequest();
});
describe("Emitter", function() {
var emitter;
emitter = null;
beforeEach(function() {
return emitter = new Dropzone.prototype.Emitter();
});
it(".on() should return the object itself", function() {
return (emitter.on("test", function() {})).should.equal(emitter);
});
it(".on() should properly register listeners", function() {
var callback, callback2;
(emitter._callbacks === void 0).should.be["true"];
callback = function() {};
callback2 = function() {};
emitter.on("test", callback);
emitter.on("test", callback2);
emitter.on("test2", callback);
emitter._callbacks.test.length.should.equal(2);
emitter._callbacks.test[0].should.equal(callback);
emitter._callbacks.test[1].should.equal(callback2);
emitter._callbacks.test2.length.should.equal(1);
return emitter._callbacks.test2[0].should.equal(callback);
});
it(".emit() should return the object itself", function() {
return emitter.emit('test').should.equal(emitter);
});
it(".emit() should properly invoke all registered callbacks with arguments", function() {
var callCount1, callCount12, callCount2, callback1, callback12, callback2;
callCount1 = 0;
callCount12 = 0;
callCount2 = 0;
callback1 = function(var1, var2) {
callCount1++;
var1.should.equal('callback1 var1');
return var2.should.equal('callback1 var2');
};
callback12 = function(var1, var2) {
callCount12++;
var1.should.equal('callback1 var1');
return var2.should.equal('callback1 var2');
};
callback2 = function(var1, var2) {
callCount2++;
var1.should.equal('callback2 var1');
return var2.should.equal('callback2 var2');
};
emitter.on("test1", callback1);
emitter.on("test1", callback12);
emitter.on("test2", callback2);
callCount1.should.equal(0);
callCount12.should.equal(0);
callCount2.should.equal(0);
emitter.emit("test1", "callback1 var1", "callback1 var2");
callCount1.should.equal(1);
callCount12.should.equal(1);
callCount2.should.equal(0);
emitter.emit("test2", "callback2 var1", "callback2 var2");
callCount1.should.equal(1);
callCount12.should.equal(1);
callCount2.should.equal(1);
emitter.emit("test1", "callback1 var1", "callback1 var2");
callCount1.should.equal(2);
callCount12.should.equal(2);
return callCount2.should.equal(1);
});
return describe(".off()", function() {
var callback1, callback2, callback3, callback4;
callback1 = function() {};
callback2 = function() {};
callback3 = function() {};
callback4 = function() {};
beforeEach(function() {
return emitter._callbacks = {
'test1': [callback1, callback2],
'test2': [callback3],
'test3': [callback1, callback4],
'test4': []
};
});
it("should work without any listeners", function() {
var emt;
emitter._callbacks = void 0;
emt = emitter.off();
emitter._callbacks.should.eql({});
return emt.should.equal(emitter);
});
it("should properly remove all event listeners", function() {
var emt;
emt = emitter.off();
emitter._callbacks.should.eql({});
return emt.should.equal(emitter);
});
it("should properly remove all event listeners for specific event", function() {
var emt;
emitter.off("test1");
(emitter._callbacks["test1"] === void 0).should.be["true"];
emitter._callbacks["test2"].length.should.equal(1);
emitter._callbacks["test3"].length.should.equal(2);
emt = emitter.off("test2");
(emitter._callbacks["test2"] === void 0).should.be["true"];
return emt.should.equal(emitter);
});
return it("should properly remove specific event listener", function() {
var emt;
emitter.off("test1", callback1);
emitter._callbacks["test1"].length.should.equal(1);
emitter._callbacks["test1"][0].should.equal(callback2);
emitter._callbacks["test3"].length.should.equal(2);
emt = emitter.off("test3", callback4);
emitter._callbacks["test3"].length.should.equal(1);
emitter._callbacks["test3"][0].should.equal(callback1);
return emt.should.equal(emitter);
});
});
});
describe("static functions", function() {
describe("Dropzone.createElement()", function() {
var element;
element = Dropzone.createElement("<div class=\"test\"><span>Hallo</span></div>");
it("should properly create an element from a string", function() {
return element.tagName.should.equal("DIV");
});
it("should properly add the correct class", function() {
return element.classList.contains("test").should.be.ok;
});
it("should properly create child elements", function() {
return element.querySelector("span").tagName.should.equal("SPAN");
});
return it("should always return only one element", function() {
element = Dropzone.createElement("<div></div><span></span>");
return element.tagName.should.equal("DIV");
});
});
describe("Dropzone.elementInside()", function() {
var child1, child2, element;
element = Dropzone.createElement("<div id=\"test\"><div class=\"child1\"><div class=\"child2\"></div></div></div>");
document.body.appendChild(element);
child1 = element.querySelector(".child1");
child2 = element.querySelector(".child2");
after(function() {
return document.body.removeChild(element);
});
it("should return yes if elements are the same", function() {
return Dropzone.elementInside(element, element).should.be.ok;
});
it("should return yes if element is direct child", function() {
return Dropzone.elementInside(child1, element).should.be.ok;
});
it("should return yes if element is some child", function() {
Dropzone.elementInside(child2, element).should.be.ok;
return Dropzone.elementInside(child2, document.body).should.be.ok;
});
return it("should return no unless element is some child", function() {
Dropzone.elementInside(element, child1).should.not.be.ok;
return Dropzone.elementInside(document.body, child1).should.not.be.ok;
});
});
describe("Dropzone.optionsForElement()", function() {
var element, testOptions;
testOptions = {
url: "/some/url",
method: "put"
};
before(function() {
return Dropzone.options.testElement = testOptions;
});
after(function() {
return delete Dropzone.options.testElement;
});
element = document.createElement("div");
it("should take options set in Dropzone.options from camelized id", function() {
element.id = "test-element";
return Dropzone.optionsForElement(element).should.equal(testOptions);
});
it("should return undefined if no options set", function() {
element.id = "test-element2";
return expect(Dropzone.optionsForElement(element)).to.equal(void 0);
});
it("should return undefined and not throw if it's a form with an input element of the name 'id'", function() {
element = Dropzone.createElement("<form><input name=\"id\" /</form>");
return expect(Dropzone.optionsForElement(element)).to.equal(void 0);
});
return it("should ignore input fields with the name='id'", function() {
element = Dropzone.createElement("<form id=\"test-element\"><input type=\"hidden\" name=\"id\" value=\"fooo\" /></form>");
return Dropzone.optionsForElement(element).should.equal(testOptions);
});
});
describe("Dropzone.forElement()", function() {
var dropzone, element;
element = document.createElement("div");
element.id = "some-test-element";
dropzone = null;
before(function() {
document.body.appendChild(element);
return dropzone = new Dropzone(element, {
url: "/test"
});
});
after(function() {
dropzone.disable();
return document.body.removeChild(element);
});
it("should throw an exception if no dropzone attached", function() {
return expect(function() {
return Dropzone.forElement(document.createElement("div"));
}).to["throw"]("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone.");
});
it("should accept css selectors", function() {
return expect(Dropzone.forElement("#some-test-element")).to.equal(dropzone);
});
return it("should accept native elements", function() {
return expect(Dropzone.forElement(element)).to.equal(dropzone);
});
});
describe("Dropzone.discover()", function() {
var element1, element2, element3;
element1 = document.createElement("div");
element1.className = "dropzone";
element2 = element1.cloneNode();
element3 = element1.cloneNode();
element1.id = "test-element-1";
element2.id = "test-element-2";
element3.id = "test-element-3";
describe("specific options", function() {
before(function() {
Dropzone.options.testElement1 = {
url: "test-url"
};
Dropzone.options.testElement2 = false;
document.body.appendChild(element1);
document.body.appendChild(element2);
return Dropzone.discover();
});
after(function() {
document.body.removeChild(element1);
return document.body.removeChild(element2);
});
it("should find elements with a .dropzone class", function() {
return element1.dropzone.should.be.ok;
});
return it("should not create dropzones with disabled options", function() {
return expect(element2.dropzone).to.not.be.ok;
});
});
return describe("Dropzone.autoDiscover", function() {
before(function() {
Dropzone.options.testElement3 = {
url: "test-url"
};
return document.body.appendChild(element3);
});
after(function() {
return document.body.removeChild(element3);
});
it("should create dropzones even if Dropzone.autoDiscover == false", function() {
Dropzone.autoDiscover = false;
Dropzone.discover();
return expect(element3.dropzone).to.be.ok;
});
return it("should not automatically be called if Dropzone.autoDiscover == false", function() {
Dropzone.autoDiscover = false;
Dropzone.discover = function() {
return expect(false).to.be.ok;
};
return Dropzone._autoDiscoverFunction();
});
});
});
describe("Dropzone.isValidFile()", function() {
it("should return true if called without acceptedFiles", function() {
return Dropzone.isValidFile({
type: "some/type"
}, null).should.be.ok;
});
it("should properly validate if called with concrete mime types", function() {
var acceptedMimeTypes;
acceptedMimeTypes = "text/html,image/jpeg,application/json";
Dropzone.isValidFile({
type: "text/html"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
type: "image/jpeg"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
type: "application/json"
}, acceptedMimeTypes).should.be.ok;
return Dropzone.isValidFile({
type: "image/bmp"
}, acceptedMimeTypes).should.not.be.ok;
});
it("should properly validate if called with base mime types", function() {
var acceptedMimeTypes;
acceptedMimeTypes = "text/*,image/*,application/*";
Dropzone.isValidFile({
type: "text/html"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
type: "image/jpeg"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
type: "application/json"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
type: "image/bmp"
}, acceptedMimeTypes).should.be.ok;
return Dropzone.isValidFile({
type: "some/type"
}, acceptedMimeTypes).should.not.be.ok;
});
it("should properly validate if called with mixed mime types", function() {
var acceptedMimeTypes;
acceptedMimeTypes = "text/*,image/jpeg,application/*";
Dropzone.isValidFile({
type: "text/html"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
type: "image/jpeg"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
type: "image/bmp"
}, acceptedMimeTypes).should.not.be.ok;
Dropzone.isValidFile({
type: "application/json"
}, acceptedMimeTypes).should.be.ok;
return Dropzone.isValidFile({
type: "some/type"
}, acceptedMimeTypes).should.not.be.ok;
});
it("should properly validate even with spaces in between", function() {
var acceptedMimeTypes;
acceptedMimeTypes = "text/html , image/jpeg, application/json";
Dropzone.isValidFile({
type: "text/html"
}, acceptedMimeTypes).should.be.ok;
return Dropzone.isValidFile({
type: "image/jpeg"
}, acceptedMimeTypes).should.be.ok;
});
return it("should properly validate extensions", function() {
var acceptedMimeTypes;
acceptedMimeTypes = "text/html , image/jpeg, .pdf ,.png";
Dropzone.isValidFile({
name: "somxsfsd",
type: "text/html"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
name: "somesdfsdf",
type: "image/jpeg"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
name: "somesdfadfadf",
type: "application/json"
}, acceptedMimeTypes).should.not.be.ok;
Dropzone.isValidFile({
name: "some-file file.pdf",
type: "random/type"
}, acceptedMimeTypes).should.be.ok;
Dropzone.isValidFile({
name: "some-file.pdf file.gif",
type: "random/type"
}, acceptedMimeTypes).should.not.be.ok;
return Dropzone.isValidFile({
name: "some-file file.png",
type: "random/type"
}, acceptedMimeTypes).should.be.ok;
});
});
return describe("Dropzone.confirm", function() {
beforeEach(function() {
return sinon.stub(window, "confirm");
});
afterEach(function() {
return window.confirm.restore();
});
it("should forward to window.confirm and call the callbacks accordingly", function() {
var accepted, rejected;
accepted = rejected = false;
window.confirm.returns(true);
Dropzone.confirm("test question", (function() {
return accepted = true;
}), (function() {
return rejected = true;
}));
window.confirm.args[0][0].should.equal("test question");
accepted.should.equal(true);
rejected.should.equal(false);
accepted = rejected = false;
window.confirm.returns(false);
Dropzone.confirm("test question 2", (function() {
return accepted = true;
}), (function() {
return rejected = true;
}));
window.confirm.args[1][0].should.equal("test question 2");
accepted.should.equal(false);
return rejected.should.equal(true);
});
return it("should not error if rejected is not provided", function() {
var accepted, rejected;
accepted = rejected = false;
window.confirm.returns(false);
Dropzone.confirm("test question", (function() {
return accepted = true;
}));
window.confirm.args[0][0].should.equal("test question");
accepted.should.equal(false);
return rejected.should.equal(false);
});
});
});
describe("Dropzone.getElement() / getElements()", function() {
var tmpElements;
tmpElements = [];
beforeEach(function() {
tmpElements = [];
tmpElements.push(Dropzone.createElement("<div class=\"tmptest\"></div>"));
tmpElements.push(Dropzone.createElement("<div id=\"tmptest1\" class=\"random\"></div>"));
tmpElements.push(Dropzone.createElement("<div class=\"random div\"></div>"));
return tmpElements.forEach(function(el) {
return document.body.appendChild(el);
});
});
afterEach(function() {
return tmpElements.forEach(function(el) {
return document.body.removeChild(el);
});
});
describe(".getElement()", function() {
it("should accept a string", function() {
var el;
el = Dropzone.getElement(".tmptest");
el.should.equal(tmpElements[0]);
el = Dropzone.getElement("#tmptest1");
return el.should.equal(tmpElements[1]);
});
it("should accept a node", function() {
var el;
el = Dropzone.getElement(tmpElements[2]);
return el.should.equal(tmpElements[2]);
});
return it("should fail if invalid selector", function() {
var errorMessage;
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector or a plain HTML element.";
expect(function() {
return Dropzone.getElement("lblasdlfsfl", "clickable");
}).to["throw"](errorMessage);
expect(function() {
return Dropzone.getElement({
"lblasdlfsfl": "lblasdlfsfl"
}, "clickable");
}).to["throw"](errorMessage);
return expect(function() {
return Dropzone.getElement(["lblasdlfsfl"], "clickable");
}).to["throw"](errorMessage);
});
});
return describe(".getElements()", function() {
it("should accept a list of strings", function() {
var els;
els = Dropzone.getElements([".tmptest", "#tmptest1"]);
return els.should.eql([tmpElements[0], tmpElements[1]]);
});
it("should accept a list of nodes", function() {
var els;
els = Dropzone.getElements([tmpElements[0], tmpElements[2]]);
return els.should.eql([tmpElements[0], tmpElements[2]]);
});
it("should accept a mixed list", function() {
var els;
els = Dropzone.getElements(["#tmptest1", tmpElements[2]]);
return els.should.eql([tmpElements[1], tmpElements[2]]);
});
it("should accept a string selector", function() {
var els;
els = Dropzone.getElements(".random");
return els.should.eql([tmpElements[1], tmpElements[2]]);
});
it("should accept a single node", function() {
var els;
els = Dropzone.getElements(tmpElements[1]);
return els.should.eql([tmpElements[1]]);
});
return it("should fail if invalid selector", function() {
var errorMessage;
errorMessage = "Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those.";
expect(function() {
return Dropzone.getElements("lblasdlfsfl", "clickable");
}).to["throw"](errorMessage);
return expect(function() {
return Dropzone.getElements(["lblasdlfsfl"], "clickable");
}).to["throw"](errorMessage);
});
});
});
describe("constructor()", function() {
var dropzone;
dropzone = null;
afterEach(function() {
if (dropzone != null) {
return dropzone.destroy();
}
});
it("should throw an exception if the element is invalid", function() {
return expect(function() {
return dropzone = new Dropzone("#invalid-element");
}).to["throw"]("Invalid dropzone element.");
});
it("should throw an exception if assigned twice to the same element", function() {
var element;
element = document.createElement("div");
dropzone = new Dropzone(element, {
url: "url"
});
return expect(function() {
return new Dropzone(element, {
url: "url"
});
}).to["throw"]("Dropzone already attached.");
});
it("should throw an exception if both acceptedFiles and acceptedMimeTypes are specified", function() {
var element;
element = document.createElement("div");
return expect(function() {
return dropzone = new Dropzone(element, {
url: "test",
acceptedFiles: "param",
acceptedMimeTypes: "types"
});
}).to["throw"]("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated.");
});
it("should set itself as element.dropzone", function() {
var element;
element = document.createElement("div");
dropzone = new Dropzone(element, {
url: "url"
});
return element.dropzone.should.equal(dropzone);
});
it("should add itself to Dropzone.instances", function() {
var element;
element = document.createElement("div");
dropzone = new Dropzone(element, {
url: "url"
});
return Dropzone.instances[Dropzone.instances.length - 1].should.equal(dropzone);
});
it("should use the action attribute not the element with the name action", function() {
var element;
element = Dropzone.createElement("<form action=\"real-action\"><input type=\"hidden\" name=\"action\" value=\"wrong-action\" /></form>");
dropzone = new Dropzone(element);
return dropzone.options.url.should.equal("real-action");
});
return describe("options", function() {
var element, element2;
element = null;
element2 = null;
beforeEach(function() {
element = document.createElement("div");
element.id = "test-element";
element2 = document.createElement("div");
element2.id = "test-element2";
return Dropzone.options.testElement = {
url: "/some/url",
parallelUploads: 10
};
});
afterEach(function() {
return delete Dropzone.options.testElement;
});
it("should take the options set in Dropzone.options", function() {
dropzone = new Dropzone(element);
dropzone.options.url.should.equal("/some/url");
return dropzone.options.parallelUploads.should.equal(10);
});
it("should prefer passed options over Dropzone.options", function() {
dropzone = new Dropzone(element, {
url: "/some/other/url"
});
return dropzone.options.url.should.equal("/some/other/url");
});
it("should take the default options if nothing set in Dropzone.options", function() {
dropzone = new Dropzone(element2, {
url: "/some/url"
});
return dropzone.options.parallelUploads.should.equal(2);
});
it("should call the fallback function if forceFallback == true", function(done) {
return dropzone = new Dropzone(element, {
url: "/some/other/url",
forceFallback: true,
fallback: function() {
return done();
}
});
});
it("should set acceptedFiles if deprecated acceptedMimetypes option has been passed", function() {
dropzone = new Dropzone(element, {
url: "/some/other/url",
acceptedMimeTypes: "my/type"
});
return dropzone.options.acceptedFiles.should.equal("my/type");
});
return describe("options.clickable", function() {
var clickableElement;
clickableElement = null;
dropzone = null;
beforeEach(function() {
clickableElement = document.createElement("div");
clickableElement.className = "some-clickable";
return document.body.appendChild(clickableElement);
});
afterEach(function() {
document.body.removeChild(clickableElement);
if (dropzone != null) {
return dropzone.destroy;
}
});
it("should use the default element if clickable == true", function() {
dropzone = new Dropzone(element, {
clickable: true
});
return dropzone.clickableElements.should.eql([dropzone.element]);
});
it("should lookup the element if clickable is a CSS selector", function() {
dropzone = new Dropzone(element, {
clickable: ".some-clickable"
});
return dropzone.clickableElements.should.eql([clickableElement]);
});
it("should simply use the provided element", function() {
dropzone = new Dropzone(element, {
clickable: clickableElement
});
return dropzone.clickableElements.should.eql([clickableElement]);
});
it("should accept multiple clickable elements", function() {
dropzone = new Dropzone(element, {
clickable: [document.body, ".some-clickable"]
});
return dropzone.clickableElements.should.eql([document.body, clickableElement]);
});
return it("should throw an exception if the element is invalid", function() {
return expect(function() {
return dropzone = new Dropzone(element, {
clickable: ".some-invalid-clickable"
});
}).to["throw"]("Invalid `clickable` option provided. Please provide a CSS selector, a plain HTML element or a list of those.");
});
});
});
});
describe("init()", function() {
describe("clickable", function() {
var dropzone, dropzones, name, _results;
dropzones = {
"using acceptedFiles": new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), {
clickable: true,
acceptedFiles: "audio/*,video/*"
}),
"using acceptedMimeTypes": new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), {
clickable: true,
acceptedMimeTypes: "audio/*,video/*"
})
};
it("should not add an accept attribute if no acceptParameter", function() {
var dropzone;
dropzone = new Dropzone(Dropzone.createElement("<form action=\"/\"></form>"), {
clickable: true,
acceptParameter: null,
acceptedMimeTypes: null
});
return dropzone.hiddenFileInput.hasAttribute("accept").should.be["false"];
});
_results = [];
for (name in dropzones) {
dropzone = dropzones[name];
_results.push(describe(name, function() {
return (function(dropzone) {
it("should create a hidden file input if clickable", function() {
dropzone.hiddenFileInput.should.be.ok;
return dropzone.hiddenFileInput.tagName.should.equal("INPUT");
});
it("should use the acceptParameter", function() {
return dropzone.hiddenFileInput.getAttribute("accept").should.equal("audio/*,video/*");
});
return it("should create a new input element when something is selected to reset the input field", function() {
var event, hiddenFileInput, i, _i, _results1;
_results1 = [];
for (i = _i = 0; _i <= 3; i = ++_i) {
hiddenFileInput = dropzone.hiddenFileInput;
event = document.createEvent("HTMLEvents");
event.initEvent("change", true, true);
hiddenFileInput.dispatchEvent(event);
dropzone.hiddenFileInput.should.not.equal(hiddenFileInput);
_results1.push(Dropzone.elementInside(hiddenFileInput, document).should.not.be.ok);
}
return _results1;
});
})(dropzone);
}));
}
return _results;
});
it("should create a .dz-message element", function() {
var dropzone, element;
element = Dropzone.createElement("<form class=\"dropzone\" action=\"/\"></form>");
dropzone = new Dropzone(element, {
clickable: true,
acceptParameter: null,
acceptedMimeTypes: null
});
return element.querySelector(".dz-message").should.be["instanceof"](Element);
});
return it("should not create a .dz-message element if there already is one", function() {
var dropzone, element, msg;
element = Dropzone.createElement("<form class=\"dropzone\" action=\"/\"></form>");
msg = Dropzone.createElement("<div class=\"dz-message\">TEST</div>");
element.appendChild(msg);
dropzone = new Dropzone(element, {
clickable: true,
acceptParameter: null,
acceptedMimeTypes: null
});
element.querySelector(".dz-message").should.equal(msg);
return element.querySelectorAll(".dz-message").length.should.equal(1);
});
});
describe("options", function() {
var dropzone, element;
element = null;
dropzone = null;
beforeEach(function() {
element = Dropzone.createElement("<div></div>");
return dropzone = new Dropzone(element, {
maxFilesize: 4,
url: "url",
acceptedMimeTypes: "audio/*,image/png",
maxFiles: 3
});
});
return describe("file specific", function() {
var file;
file = null;
beforeEach(function() {
file = {
name: "test name",
size: 2 * 1024 * 1024,
width: 200,
height: 100
};
return dropzone.options.addedfile.call(dropzone, file);
});
describe(".addedFile()", function() {
return it("should properly create the previewElement", function() {
file.previewElement.should.be["instanceof"](Element);
file.previewElement.querySelector("[data-dz-name]").innerHTML.should.eql("test name");
return file.previewElement.querySelector("[data-dz-size]").innerHTML.should.eql("<strong>2.1</strong> MB");
});
});
describe(".error()", function() {
it("should properly insert the error", function() {
dropzone.options.error.call(dropzone, file, "test message");
return file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql("test message");
});
return it("should properly insert the error when provided with an object containing the error", function() {
dropzone.options.error.call(dropzone, file, {
error: "test message"
});
return file.previewElement.querySelector("[data-dz-errormessage]").innerHTML.should.eql("test message");
});
});
describe(".thumbnail()", function() {
return it("should properly insert the error", function() {
var thumbnail, transparentGif;
transparentGif = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
dropzone.options.thumbnail.call(dropzone, file, transparentGif);
thumbnail = file.previewElement.querySelector("[data-dz-thumbnail]");
thumbnail.src.should.eql(transparentGif);
return thumbnail.alt.should.eql("test name");
});
});
describe(".uploadprogress()", function() {
return it("should properly set the width", function() {
dropzone.options.uploadprogress.call(dropzone, file, 0);
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("0%");
dropzone.options.uploadprogress.call(dropzone, file, 80);
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("80%");
dropzone.options.uploadprogress.call(dropzone, file, 90);
file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("90%");
dropzone.options.uploadprogress.call(dropzone, file, 100);
return file.previewElement.querySelector("[data-dz-uploadprogress]").style.width.should.eql("100%");
});
});
return describe(".resize()", function() {
describe("with default thumbnail settings", function() {
return it("should properly return target dimensions", function() {
var info;
info = dropzone.options.resize.call(dropzone, file);
info.optWidth.should.eql(120);
return info.optHeight.should.eql(120);
});
});
return describe("with null thumbnail settings", function() {
return it("should properly return target dimensions", function() {
var i, info, setting, testSettings, _i, _len, _results;
testSettings = [[null, null], [null, 150], [150, null]];
_results = [];
for (i = _i = 0, _len = testSettings.length; _i < _len; i = ++_i) {
setting = testSettings[i];
dropzone.options.thumbnailWidth = setting[0];
dropzone.options.thumbnailHeight = setting[1];
info = dropzone.options.resize.call(dropzone, file);
if (i === 0) {
info.optWidth.should.eql(200);
info.optHeight.should.eql(100);
}
if (i === 1) {
info.optWidth.should.eql(300);
info.optHeight.should.eql(150);
}
if (i === 2) {
info.optWidth.should.eql(150);
_results.push(info.optHeight.should.eql(75));
} else {
_results.push(void 0);
}
}
return _results;
});
});
});
});
});
describe("instance", function() {
var dropzone, element, requests;
element = null;
dropzone = null;
requests = null;
beforeEach(function() {
requests = [];
xhr.onCreate = function(xhr) {
return requests.push(xhr);
};
element = Dropzone.createElement("<div></div>");
document.body.appendChild(element);
return dropzone = new Dropzone(element, {
maxFilesize: 4,
maxFiles: 100,
url: "url",
acceptedMimeTypes: "audio/*,image/png",
uploadprogress: function() {}
});
});
afterEach(function() {
document.body.removeChild(element);
dropzone.destroy();
return xhr.restore();
});
describe(".accept()", function() {
it("should pass if the filesize is OK", function() {
return dropzone.accept({
size: 2 * 1024 * 1024,
type: "audio/mp3"
}, function(err) {
return expect(err).to.be.undefined;
});
});
it("shouldn't pass if the filesize is too big", function() {
return dropzone.accept({
size: 10 * 1024 * 1024,
type: "audio/mp3"
}, function(err) {
return err.should.eql("File is too big (10MiB). Max filesize: 4MiB.");
});
});
it("should properly accept files which mime types are listed in acceptedFiles", function() {
dropzone.accept({
type: "audio/mp3"
}, function(err) {
return expect(err).to.be.undefined;
});
dropzone.accept({
type: "image/png"
}, function(err) {
return expect(err).to.be.undefined;
});
return dropzone.accept({
type: "audio/wav"
}, function(err) {
return expect(err).to.be.undefined;
});
});
it("should properly reject files when the mime type isn't listed in acceptedFiles", function() {
return dropzone.accept({
type: "image/jpeg"
}, function(err) {
return err.should.eql("You can't upload files of this type.");
});
});
it("should fail if maxFiles has been exceeded and call the event maxfilesexceeded", function() {
var called, file;
sinon.stub(dropzone, "getAcceptedFiles");
file = {
type: "audio/mp3"
};
dropzone.getAcceptedFiles.returns({
length: 99
});
dropzone.options.dictMaxFilesExceeded = "You can only upload {{maxFiles}} files.";
called = false;
dropzone.on("maxfilesexceeded", function(lfile) {
lfile.should.equal(file);
return called = true;
});
dropzone.accept(file, function(err) {
return expect(err).to.be.undefined;
});
called.should.not.be.ok;
dropzone.getAcceptedFiles.returns({
length: 100
});
dropzone.accept(file, function(err) {
return expect(err).to.equal("You can only upload 100 files.");
});
called.should.be.ok;
return dropzone.getAcceptedFiles.restore();
});
return it("should properly handle if maxFiles is 0", function() {
var called, file;
file = {
type: "audio/mp3"
};
dropzone.options.maxFiles = 0;
called = false;
dropzone.on("maxfilesexceeded", function(lfile) {
lfile.should.equal(file);
return called = true;
});
dropzone.accept(file, function(err) {
return expect(err).to.equal("You can not upload any more files.");
});
return called.should.be.ok;
});
});
describe(".removeFile()", function() {
return it("should abort uploading if file is currently being uploaded", function(done) {
var mockFile;
mockFile = getMockFile();
dropzone.uploadFile = function(file) {};
dropzone.accept = function(file, done) {
return done();
};
sinon.stub(dropzone, "cancelUpload");
dropzone.addFile(mockFile);
return setTimeout(function() {
mockFile.status.should.equal(Dropzone.UPLOADING);
dropzone.getUploadingFiles()[0].should.equal(mockFile);
dropzone.cancelUpload.callCount.should.equal(0);
dropzone.removeFile(mockFile);
dropzone.cancelUpload.callCount.should.equal(1);
return done();
}, 10);
});
});
describe(".cancelUpload()", function() {
it("should properly cancel upload if file currently uploading", function(done) {
var mockFile;
mockFile = getMockFile();
dropzone.accept = function(file, done) {
return done();
};
dropzone.addFile(mockFile);
return setTimeout(function() {
mockFile.status.should.equal(Dropzone.UPLOADING);
dropzone.getUploadingFiles()[0].should.equal(mockFile);
dropzone.cancelUpload(mockFile);
mockFile.status.should.equal(Dropzone.CANCELED);
dropzone.getUploadingFiles().length.should.equal(0);
dropzone.getQueuedFiles().length.should.equal(0);
return done();
}, 10);
});
it("should properly cancel the upload if file is not yet uploading", function() {
var mockFile;
mockFile = getMockFile();
dropzone.accept = function(file, done) {
return done();
};
dropzone.options.parallelUploads = 0;
dropzone.addFile(mockFile);
mockFile.status.should.equal(Dropzone.QUEUED);
dropzone.getQueuedFiles()[0].should.equal(mockFile);
dropzone.cancelUpload(mockFile);
mockFile.status.should.equal(Dropzone.CANCELED);
dropzone.getQueuedFiles().length.should.equal(0);
return dropzone.getUploadingFiles().length.should.equal(0);
});
it("should call processQueue()", function(done) {
var mockFile;
mockFile = getMockFile();
dropzone.accept = function(file, done) {
return done();
};
dropzone.options.parallelUploads = 0;
sinon.spy(dropzone, "processQueue");
dropzone.addFile(mockFile);
return setTimeout(function() {
dropzone.processQueue.callCount.should.equal(1);
dropzone.cancelUpload(mockFile);
dropzone.processQueue.callCount.should.equal(2);
return done();
}, 10);
});
return it("should properly cancel all files with the same XHR if uploadMultiple is true", function(done) {
var mock1, mock2, mock3;
mock1 = getMockFile();
mock2 = getMockFile();
mock3 = getMockFile();
dropzone.accept = function(file, done) {
return done();
};
dropzone.options.uploadMultiple = true;
dropzone.options.parallelUploads = 3;
sinon.spy(dropzone, "processFiles");
dropzone.addFile(mock1);
dropzone.addFile(mock2);
dropzone.addFile(mock3);
return setTimeout(function() {
var _ref;
dropzone.processFiles.callCount.should.equal(1);
sinon.spy(mock1.xhr, "abort");
dropzone.cancelUpload(mock1);
expect((mock1.xhr === (_ref = mock2.xhr) && _ref === mock3.xhr)).to.be.ok;
mock1.status.should.equal(Dropzone.CANCELED);
mock2.status.should.equal(Dropzone.CANCELED);
mock3.status.should.equal(Dropzone.CANCELED);
mock1.xhr.abort.callCount.should.equal(1);
return done();
}, 10);
});
});
describe(".disable()", function() {
return it("should properly cancel all pending uploads", function(done) {
dropzone.accept = function(file, done) {
return done();
};
dropzone.options.parallelUploads = 1;
dropzone.addFile(getMockFile());
dropzone.addFile(getMockFile());
return setTimeout(function() {
dropzone.getUploadingFiles().length.should.equal(1);
dropzone.getQueuedFiles().length.should.equal(1);
dropzone.files.length.should.equal(2);
sinon.spy(requests[0], "abort");
requests[0].abort.callCount.should.equal(0);
dropzone.disable();
requests[0].abort.callCount.should.equal(1);
dropzone.getUploadingFiles().length.should.equal(0);
dropzone.getQueuedFiles().length.should.equal(0);
dropzone.files.length.should.equal(2);
dropzone.files[0].status.should.equal(Dropzone.CANCELED);
dropzone.files[1].status.should.equal(Dropzone.CANCELED);
return done();
}, 10);
});
});
describe(".destroy()", function() {
it("should properly cancel all pending uploads and remove all file references", function(done) {
dropzone.accept = function(file, done) {
return done();
};
dropzone.options.parallelUploads = 1;
dropzone.addFile(getMockFile());
dropzone.addFile(getMockFile());
return setTimeout(function() {
dropzone.getUploadingFiles().length.should.equal(1);
dropzone.getQueuedFiles().length.should.equal(1);
dropzone.files.length.should.equal(2);
sinon.spy(dropzone, "disable");
dropzone.destroy();
dropzone.disable.callCount.should.equal(1);
element.should.not.have.property("dropzone");
return done();
}, 10);
});
it("should be able to create instance of dropzone on the same element after destroy", function() {
dropzone.destroy();
return (function() {
return new Dropzone(element, {
maxFilesize: 4,
url: "url",
acceptedMimeTypes: "audio/*,image/png",
uploadprogress: function() {}
});
}).should.not["throw"](Error);
});
return it("should remove itself from Dropzone.instances", function() {
(Dropzone.instances.indexOf(dropzone) !== -1).should.be.ok;
dropzone.destroy();
return (Dropzone.instances.indexOf(dropzone) === -1).should.be.ok;
});
});
describe(".filesize()", function() {
it("should convert to KiloBytes, etc..", function() {
dropzone.options.filesizeBase.should.eql(1000);
dropzone.filesize(2 * 1000 * 1000).should.eql("<strong>2</strong> MB");
dropzone.filesize(2 * 1024 * 1024).should.eql("<strong>2.1</strong> MB");
dropzone.filesize(2 * 1000 * 1000 * 1000).should.eql("<strong>2</strong> GB");
dropzone.filesize(2 * 1024 * 1024 * 1024).should.eql("<strong>2.1</strong> GB");
dropzone.filesize(2.5111 * 1000 * 1000 * 1000).should.eql("<strong>2.5</strong> GB");
dropzone.filesize(1.1 * 1000).should.eql("<strong>1.1</strong> KB");
return dropzone.filesize(999 * 1000).should.eql("<strong>1</strong> MB");
});
return it("should convert to KibiBytes, etc.. when the filesizeBase is changed to 1024", function() {
dropzone.options.filesizeBase = 1024;
dropzone.filesize(2 * 1024 * 1024).should.eql("<strong>2</strong> MB");
return dropzone.filesize(2 * 1000 * 1000).should.eql("<strong>1.9</strong> MB");
});
});
describe("._updateMaxFilesReachedClass()", function() {
it("should properly add the dz-max-files-reached class", function() {
dropzone.getAcceptedFiles = function() {
return {
length: 10
};
};
dropzone.options.maxFiles = 10;
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok;
dropzone._updateMaxFilesReachedClass();
return dropzone.element.classList.contains("dz-max-files-reached").should.be.ok;
});
it("should fire the 'maxfilesreached' event when appropriate", function() {
var spy;
spy = sinon.spy();
dropzone.on("maxfilesreached", function() {
return spy();
});
dropzone.getAcceptedFiles = function() {
return {
length: 9
};
};
dropzone.options.maxFiles = 10;
dropzone._updateMaxFilesReachedClass();
spy.should.not.have.been.called;
dropzone.getAcceptedFiles = function() {
return {
length: 10
};
};
dropzone._updateMaxFilesReachedClass();
spy.should.have.been.called;
dropzone.getAcceptedFiles = function() {
return {
length: 11
};
};
dropzone._updateMaxFilesReachedClass();
return spy.should.have.been.calledOnce;
});
return it("should properly remove the dz-max-files-reached class", function() {
dropzone.getAcceptedFiles = function() {
return {
length: 10
};
};
dropzone.options.maxFiles = 10;
dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok;
dropzone._updateMaxFilesReachedClass();
dropzone.element.classList.contains("dz-max-files-reached").should.be.ok;
dropzone.getAcceptedFiles = function() {
return {
length: 9
};
};
dropzone._updateMaxFilesReachedClass();
return dropzone.element.classList.contains("dz-max-files-reached").should.not.be.ok;
});
});
return describe("events", function() {
return describe("progress updates", function() {
return it("should properly emit a totaluploadprogress event", function(done) {
var totalProgressExpectation, _called;
dropzone.files = [
{
size: 1990,
accepted: true,
status: Dropzone.UPLOADING,
upload: {
progress: 20,
total: 2000,
bytesSent: 400
}
}, {
size: 1990,
accepted: true,
status: Dropzone.UPLOADING,
upload: {
progress: 10,
total: 2000,
bytesSent: 200
}
}
];
_called = 0;
dropzone.on("totaluploadprogress", function(progress) {
progress.should.equal(totalProgressExpectation);
if (++_called === 3) {
return done();
}
});
totalProgressExpectation = 15;
dropzone.emit("uploadprogress", {});
totalProgressExpectation = 97.5;
dropzone.files[0].upload.bytesSent = 2000;
dropzone.files[1].upload.bytesSent = 1900;
dropzone.emit("uploadprogress", {});
totalProgressExpectation = 100;
dropzone.files[0].upload.bytesSent = 2000;
dropzone.files[1].upload.bytesSent = 2000;
dropzone.emit("uploadprogress", {});
dropzone.files[0].status = Dropzone.CANCELED;
return dropzone.files[1].status = Dropzone.CANCELED;
});
});
});
});
describe("helper function", function() {
var dropzone, element;
element = null;
dropzone = null;
beforeEach(function() {
element = Dropzone.createElement("<div></div>");
return dropzone = new Dropzone(element, {
url: "url"
});
});
describe("getExistingFallback()", function() {
it("should return undefined if no fallback", function() {
return expect(dropzone.getExistingFallback()).to.equal(void 0);
});
it("should only return the fallback element if it contains exactly fallback", function() {
element.appendChild(Dropzone.createElement("<form class=\"fallbacks\"></form>"));
element.appendChild(Dropzone.createElement("<form class=\"sfallback\"></form>"));
return expect(dropzone.getExistingFallback()).to.equal(void 0);
});
it("should return divs as fallback", function() {
var fallback;
fallback = Dropzone.createElement("<form class=\" abc fallback test \"></form>");
element.appendChild(fallback);
return fallback.should.equal(dropzone.getExistingFallback());
});
return it("should return forms as fallback", function() {
var fallback;
fallback = Dropzone.createElement("<div class=\" abc fallback test \"></div>");
element.appendChild(fallback);
return fallback.should.equal(dropzone.getExistingFallback());
});
});
describe("getFallbackForm()", function() {
it("should use the paramName without [0] if uploadMultiple is false", function() {
var fallback, fileInput;
dropzone.options.uploadMultiple = false;
dropzone.options.paramName = "myFile";
fallback = dropzone.getFallbackForm();
fileInput = fallback.querySelector("input[type=file]");
return fileInput.name.should.equal("myFile");
});
return it("should properly add [0] to the file name if uploadMultiple is true", function() {
var fallback, fileInput;
dropzone.options.uploadMultiple = true;
dropzone.options.paramName = "myFile";
fallback = dropzone.getFallbackForm();
fileInput = fallback.querySelector("input[type=file]");
return fileInput.name.should.equal("myFile[0]");
});
});
describe("getAcceptedFiles() / getRejectedFiles()", function() {
var mock1, mock2, mock3, mock4;
mock1 = mock2 = mock3 = mock4 = null;
beforeEach(function() {
mock1 = getMockFile();
mock2 = getMockFile();
mock3 = getMockFile();
mock4 = getMockFile();
dropzone.options.accept = function(file, done) {
if (file === mock1 || file === mock3) {
return done();
} else {
return done("error");
}
};
dropzone.addFile(mock1);
dropzone.addFile(mock2);
dropzone.addFile(mock3);
return dropzone.addFile(mock4);
});
it("getAcceptedFiles() should only return accepted files", function() {
return dropzone.getAcceptedFiles().should.eql([mock1, mock3]);
});
return it("getRejectedFiles() should only return rejected files", function() {
return dropzone.getRejectedFiles().should.eql([mock2, mock4]);
});
});
describe("getQueuedFiles()", function() {
return it("should return all files with the status Dropzone.QUEUED", function() {
var mock1, mock2, mock3, mock4;
mock1 = getMockFile();
mock2 = getMockFile();
mock3 = getMockFile();
mock4 = getMockFile();
dropzone.options.accept = function(file, done) {
return file.done = done;
};
dropzone.addFile(mock1);
dropzone.addFile(mock2);
dropzone.addFile(mock3);
dropzone.addFile(mock4);
dropzone.getQueuedFiles().should.eql([]);
mock1.done();
mock3.done();
dropzone.getQueuedFiles().should.eql([mock1, mock3]);
mock1.status.should.equal(Dropzone.QUEUED);
mock3.status.should.equal(Dropzone.QUEUED);
mock2.status.should.equal(Dropzone.ADDED);
return mock4.status.should.equal(Dropzone.ADDED);
});
});
describe("getUploadingFiles()", function() {
return it("should return all files with the status Dropzone.UPLOADING", function(done) {
var mock1, mock2, mock3, mock4;
mock1 = getMockFile();
mock2 = getMockFile();
mock3 = getMockFile();
mock4 = getMockFile();
dropzone.options.accept = function(file, _done) {
return file.done = _done;
};
dropzone.uploadFile = function() {};
dropzone.addFile(mock1);
dropzone.addFile(mock2);
dropzone.addFile(mock3);
dropzone.addFile(mock4);
dropzone.getUploadingFiles().should.eql([]);
mock1.done();
mock3.done();
return setTimeout((function() {
dropzone.getUploadingFiles().should.eql([mock1, mock3]);
mock1.status.should.equal(Dropzone.UPLOADING);
mock3.status.should.equal(Dropzone.UPLOADING);
mock2.status.should.equal(Dropzone.ADDED);
mock4.status.should.equal(Dropzone.ADDED);
return done();
}), 10);
});
});
describe("getActiveFiles()", function() {
return it("should return all files with the status Dropzone.UPLOADING or Dropzone.QUEUED", function(done) {
var mock1, mock2, mock3, mock4;
mock1 = getMockFile();
mock2 = getMockFile();
mock3 = getMockFile();
mock4 = getMockFile();
dropzone.options.accept = function(file, _done) {
return file.done = _done;
};
dropzone.uploadFile = function() {};
dropzone.options.parallelUploads = 2;
dropzone.addFile(mock1);
dropzone.addFile(mock2);
dropzone.addFile(mock3);
dropzone.addFile(mock4);
dropzone.getActiveFiles().should.eql([]);
mock1.done();
mock3.done();
mock4.done();
return setTimeout((function() {
dropzone.getActiveFiles().should.eql([mock1, mock3, mock4]);
mock1.status.should.equal(Dropzone.UPLOADING);
mock3.status.should.equal(Dropzone.UPLOADING);
mock2.status.should.equal(Dropzone.ADDED);
mock4.status.should.equal(Dropzone.QUEUED);
return done();
}), 10);
});
});
return describe("getFilesWithStatus()", function() {
return it("should return all files with provided status", function() {
var mock1, mock2, mock3, mock4;
mock1 = getMockFile();
mock2 = getMockFile();
mock3 = getMockFile();
mock4 = getMockFile();
dropzone.options.accept = function(file, _done) {
return file.done = _done;
};
dropzone.uploadFile = function() {};
dropzone.addFile(mock1);
dropzone.addFile(mock2);
dropzone.addFile(mock3);
dropzone.addFile(mock4);
dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql([mock1, mock2, mock3, mock4]);
mock1.status = Dropzone.UPLOADING;
mock3.status = Dropzone.QUEUED;
mock4.status = Dropzone.QUEUED;
dropzone.getFilesWithStatus(Dropzone.ADDED).should.eql([mock2]);
dropzone.getFilesWithStatus(Dropzone.UPLOADING).should.eql([mock1]);
return dropzone.getFilesWithStatus(Dropzone.QUEUED).should.eql([mock3, mock4]);
});
});
});
return describe("file handling", function() {
var dropzone, mockFile;
mockFile = null;
dropzone = null;
beforeEach(function() {
var element;
mockFile = getMockFile();
element = Dropzone.createElement("<div></div>");
return dropzone = new Dropzone(element, {
url: "/the/url"
});
});
afterEach(function() {
return dropzone.destroy();
});
describe("addFile()", function() {
it("should properly set the status of the file", function() {
var doneFunction;
doneFunction = null;
dropzone.accept = function(file, done) {
return doneFunction = done;
};
dropzone.processFile = function() {};
dropzone.uploadFile = function() {};
dropzone.addFile(mockFile);
mockFile.status.should.eql(Dropzone.ADDED);
doneFunction();
mockFile.status.should.eql(Dropzone.QUEUED);
mockFile = getMockFile();
dropzone.addFile(mockFile);
mockFile.status.should.eql(Dropzone.ADDED);
doneFunction("error");
return mockFile.status.should.eql(Dropzone.ERROR);
});
it("should properly set the status of the file if autoProcessQueue is false and not call processQueue", function(done) {
var doneFunction;
doneFunction = null;
dropzone.options.autoProcessQueue = false;
dropzone.accept = function(file, done) {
return doneFunction = done;
};
dropzone.processFile = function() {};
dropzone.uploadFile = function() {};
dropzone.addFile(mockFile);
sinon.stub(dropzone, "processQueue");
mockFile.status.should.eql(Dropzone.ADDED);
doneFunction();
mockFile.status.should.eql(Dropzone.QUEUED);
dropzone.processQueue.callCount.should.equal(0);
return setTimeout((function() {
dropzone.processQueue.callCount.should.equal(0);
return done();
}), 10);
});
it("should not add the file to the queue if autoQueue is false", function() {
var doneFunction;
doneFunction = null;
dropzone.options.autoQueue = false;
dropzone.accept = function(file, done) {
return doneFunction = done;
};
dropzone.processFile = function() {};
dropzone.uploadFile = function() {};
dropzone.addFile(mockFile);
mockFile.status.should.eql(Dropzone.ADDED);
doneFunction();
return mockFile.status.should.eql(Dropzone.ADDED);
});
it("should create a remove link if configured to do so", function() {
dropzone.options.addRemoveLinks = true;
dropzone.processFile = function() {};
dropzone.uploadFile = function() {};
sinon.stub(dropzone, "processQueue");
dropzone.addFile(mockFile);
return dropzone.files[0].previewElement.querySelector("a[data-dz-remove].dz-remove").should.be.ok;
});
it("should attach an event handler to data-dz-remove links", function() {
var event, file, removeLink1, removeLink2;
dropzone.options.previewTemplate = "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n <div class=\"dz-success-mark\"><span>✔</span></div>\n <div class=\"dz-error-mark\"><span>✘</span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n <a class=\"link1\" data-dz-remove></a>\n <a class=\"link2\" data-dz-remove></a>\n</div>";
sinon.stub(dropzone, "processQueue");
dropzone.addFile(mockFile);
file = dropzone.files[0];
removeLink1 = file.previewElement.querySelector("a[data-dz-remove].link1");
removeLink2 = file.previewElement.querySelector("a[data-dz-remove].link2");
sinon.stub(dropzone, "removeFile");
event = document.createEvent("HTMLEvents");
event.initEvent("click", true, true);
removeLink1.dispatchEvent(event);
dropzone.removeFile.callCount.should.eql(1);
event = document.createEvent("HTMLEvents");
event.initEvent("click", true, true);
removeLink2.dispatchEvent(event);
return dropzone.removeFile.callCount.should.eql(2);
});
return describe("thumbnails", function() {
it("should properly queue the thumbnail creation", function(done) {
var ct_callback, ct_file, doneFunction, mock1, mock2, mock3;
doneFunction = null;
dropzone.accept = function(file, done) {
return doneFunction = done;
};
dropzone.processFile = function() {};
dropzone.uploadFile = function() {};
mock1 = getMockFile();
mock2 = getMockFile();
mock3 = getMockFile();
mock1.type = "image/jpg";
mock2.type = "image/jpg";
mock3.type = "image/jpg";
dropzone.on("thumbnail", function() {
return console.log("HII");
});
ct_file = ct_callback = null;
dropzone.createThumbnail = function(file, callback) {
ct_file = file;
return ct_callback = callback;
};
sinon.spy(dropzone, "createThumbnail");
dropzone.addFile(mock1);
dropzone.addFile(mock2);
dropzone.addFile(mock3);
dropzone.files.length.should.eql(3);
return setTimeout((function() {
dropzone.createThumbnail.callCount.should.eql(1);
mock1.should.equal(ct_file);
ct_callback();
dropzone.createThumbnail.callCount.should.eql(2);
mock2.should.equal(ct_file);
ct_callback();
dropzone.createThumbnail.callCount.should.eql(3);
mock3.should.equal(ct_file);
return done();
}), 10);
});
return describe("when file is SVG", function() {
return it("should use the SVG image itself", function(done) {
var blob, createBlob;
createBlob = function(data, type) {
var BlobBuilder, builder, e;
try {
return new Blob([data], {
type: type
});
} catch (_error) {
e = _error;
BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
builder = new BlobBuilder();
builder.append(data.buffer || data);
return builder.getBlob(type);
}
};
blob = createBlob('foo', 'image/svg+xml');
dropzone.on("thumbnail", function(file, dataURI) {
var fileReader;
file.should.equal(blob);
fileReader = new FileReader;
fileReader.onload = function() {
fileReader.result.should.equal(dataURI);
return done();
};
return fileReader.readAsDataURL(file);
});
return dropzone.createThumbnail(blob);
});
});
});
});
describe("enqueueFile()", function() {
it("should be wrapped by enqueueFiles()", function() {
var mock1, mock2, mock3;
sinon.stub(dropzone, "enqueueFile");
mock1 = getMockFile();
mock2 = getMockFile();
mock3 = getMockFile();
dropzone.enqueueFiles([mock1, mock2, mock3]);
dropzone.enqueueFile.callCount.should.equal(3);
dropzone.enqueueFile.args[0][0].should.equal(mock1);
dropzone.enqueueFile.args[1][0].should.equal(mock2);
return dropzone.enqueueFile.args[2][0].should.equal(mock3);
});
it("should fail if the file has already been processed", function() {
mockFile.status = Dropzone.ERROR;
expect((function() {
return dropzone.enqueueFile(mockFile);
})).to["throw"]("This file can't be queued because it has already been processed or was rejected.");
mockFile.status = Dropzone.COMPLETE;
expect((function() {
return dropzone.enqueueFile(mockFile);
})).to["throw"]("This file can't be queued because it has already been processed or was rejected.");
mockFile.status = Dropzone.UPLOADING;
return expect((function() {
return dropzone.enqueueFile(mockFile);
})).to["throw"]("This file can't be queued because it has already been processed or was rejected.");
});
return it("should set the status to QUEUED and call processQueue asynchronously if everything's ok", function(done) {
mockFile.status = Dropzone.ADDED;
sinon.stub(dropzone, "processQueue");
dropzone.processQueue.callCount.should.equal(0);
dropzone.enqueueFile(mockFile);
mockFile.status.should.equal(Dropzone.QUEUED);
dropzone.processQueue.callCount.should.equal(0);
return setTimeout(function() {
dropzone.processQueue.callCount.should.equal(1);
return done();
}, 10);
});
});
describe("uploadFiles()", function() {
var requests;
requests = null;
beforeEach(function() {
requests = [];
return xhr.onCreate = function(xhr) {
return requests.push(xhr);
};
});
afterEach(function() {
return xhr.restore();
});
it("should be wrapped by uploadFile()", function() {
sinon.stub(dropzone, "uploadFiles");
dropzone.uploadFile(mockFile);
dropzone.uploadFiles.callCount.should.equal(1);
return dropzone.uploadFiles.calledWith([mockFile]).should.be.ok;
});
it("should use url options if strings", function(done) {
dropzone.addFile(mockFile);
return setTimeout(function() {
expect(requests.length).to.equal(1);
expect(requests[0].url).to.equal(dropzone.options.url);
expect(requests[0].method).to.equal(dropzone.options.method);
return done();
}, 10);
});
it("should call url options if functions", function(done) {
var method, url;
method = "PUT";
url = "/custom/upload/url";
dropzone.options.method = sinon.stub().returns(method);
dropzone.options.url = sinon.stub().returns(url);
dropzone.addFile(mockFile);
return setTimeout(function() {
dropzone.options.method.callCount.should.equal(1);
dropzone.options.url.callCount.should.equal(1);
sinon.assert.calledWith(dropzone.options.method, [mockFile]);
sinon.assert.calledWith(dropzone.options.url, [mockFile]);
expect(requests.length).to.equal(1);
expect(requests[0].url).to.equal(url);
expect(requests[0].method).to.equal(method);
return done();
}, 10);
});
it("should ignore the onreadystate callback if readyState != 4", function(done) {
dropzone.addFile(mockFile);
return setTimeout(function() {
mockFile.status.should.eql(Dropzone.UPLOADING);
requests[0].status = 200;
requests[0].readyState = 3;
requests[0].onload();
mockFile.status.should.eql(Dropzone.UPLOADING);
requests[0].readyState = 4;
requests[0].onload();
mockFile.status.should.eql(Dropzone.SUCCESS);
return done();
}, 10);
});
it("should emit error and errormultiple when response was not OK", function(done) {
var complete, completemultiple, error, errormultiple;
dropzone.options.uploadMultiple = true;
error = false;
errormultiple = false;
complete = false;
completemultiple = false;
dropzone.on("error", function() {
return error = true;
});
dropzone.on("errormultiple", function() {
return errormultiple = true;
});
dropzone.on("complete", function() {
return complete = true;
});
dropzone.on("completemultiple", function() {
return completemultiple = true;
});
dropzone.addFile(mockFile);
return setTimeout(function() {
mockFile.status.should.eql(Dropzone.UPLOADING);
requests[0].status = 400;
requests[0].readyState = 4;
requests[0].onload();
expect((((true === error && error === errormultiple) && errormultiple === complete) && complete === completemultiple)).to.be.ok;
return done();
}, 10);
});
it("should include hidden files in the form and unchecked checkboxes and radiobuttons should be excluded", function(done) {
var element, formData, mock1;
element = Dropzone.createElement("<form action=\"/the/url\">\n <input type=\"hidden\" name=\"test\" value=\"hidden\" />\n <input type=\"checkbox\" name=\"unchecked\" value=\"1\" />\n <input type=\"checkbox\" name=\"checked\" value=\"value1\" checked=\"checked\" />\n <input type=\"radio\" value=\"radiovalue1\" name=\"radio1\" />\n <input type=\"radio\" value=\"radiovalue2\" name=\"radio1\" checked=\"checked\" />\n <select name=\"select\"><option value=\"1\">1</option><option value=\"2\" selected>2</option></select>\n</form>");
dropzone = new Dropzone(element, {
url: "/the/url"
});
formData = null;
dropzone.on("sending", function(file, xhr, tformData) {
formData = tformData;
return sinon.spy(tformData, "append");
});
mock1 = getMockFile();
dropzone.addFile(mock1);
return setTimeout(function() {
formData.append.callCount.should.equal(5);
formData.append.args[0][0].should.eql("test");
formData.append.args[0][1].should.eql("hidden");
formData.append.args[1][0].should.eql("checked");
formData.append.args[1][1].should.eql("value1");
formData.append.args[2][0].should.eql("radio1");
formData.append.args[2][1].should.eql("radiovalue2");
formData.append.args[3][0].should.eql("select");
formData.append.args[3][1].should.eql("2");
formData.append.args[4][0].should.eql("file");
formData.append.args[4][1].should.equal(mock1);
return done();
}, 10);
});
it("should all values of a select that has the multiple attribute", function(done) {
var element, formData, mock1;
element = Dropzone.createElement("<form action=\"/the/url\">\n <select name=\"select\" multiple>\n <option value=\"value1\">1</option>\n <option value=\"value2\" selected>2</option>\n <option value=\"value3\">3</option>\n <option value=\"value4\" selected>4</option>\n </select>\n</form>");
dropzone = new Dropzone(element, {
url: "/the/url"
});
formData = null;
dropzone.on("sending", function(file, xhr, tformData) {
formData = tformData;
return sinon.spy(tformData, "append");
});
mock1 = getMockFile();
dropzone.addFile(mock1);
return setTimeout(function() {
formData.append.callCount.should.equal(3);
formData.append.args[0][0].should.eql("select");
formData.append.args[0][1].should.eql("value2");
formData.append.args[1][0].should.eql("select");
formData.append.args[1][1].should.eql("value4");
formData.append.args[2][0].should.eql("file");
formData.append.args[2][1].should.equal(mock1);
return done();
}, 10);
});
describe("settings()", function() {
it("should correctly set `withCredentials` on the xhr object", function() {
dropzone.uploadFile(mockFile);
requests.length.should.eql(1);
requests[0].withCredentials.should.eql(false);
dropzone.options.withCredentials = true;
dropzone.uploadFile(mockFile);
requests.length.should.eql(2);
return requests[1].withCredentials.should.eql(true);
});
it("should correctly set headers on the xhr object", function() {
dropzone.options.headers = {
"Foo-Header": "foobar"
};
dropzone.uploadFile(mockFile);
requests[0].requestHeaders["Foo-Header"].should.eql('foobar');
return (requests[0].requestHeaders["Accept"] === void 0).should.be["false"];
});
it("should correctly override headers on the xhr object", function() {
dropzone.options.overrideDefaultHeaders = true;
dropzone.options.headers = {
"Foo-Header": "foobar"
};
dropzone.uploadFile(mockFile);
return (requests[0].requestHeaders["Accept"] === void 0).should.be["true"];
});
it("should properly use the paramName without [n] as file upload if uploadMultiple is false", function(done) {
var formData, mock1, mock2, sendingCount;
dropzone.options.uploadMultiple = false;
dropzone.options.paramName = "myName";
formData = [];
sendingCount = 0;
dropzone.on("sending", function(files, xhr, tformData) {
sendingCount++;
formData.push(tformData);
return sinon.spy(tformData, "append");
});
mock1 = getMockFile();
mock2 = getMockFile();
dropzone.addFile(mock1);
dropzone.addFile(mock2);
return setTimeout(function() {
sendingCount.should.equal(2);
formData.length.should.equal(2);
formData[0].append.callCount.should.equal(1);
formData[1].append.callCount.should.equal(1);
formData[0].append.args[0][0].should.eql("myName");
formData[0].append.args[0][0].should.eql("myName");
return done();
}, 10);
});
return it("should properly use the paramName with [n] as file upload if uploadMultiple is true", function(done) {
var formData, mock1, mock2, sendingCount, sendingMultipleCount;
dropzone.options.uploadMultiple = true;
dropzone.options.paramName = "myName";
formData = null;
sendingMultipleCount = 0;
sendingCount = 0;
dropzone.on("sending", function(file, xhr, tformData) {
return sendingCount++;
});
dropzone.on("sendingmultiple", function(files, xhr, tformData) {
sendingMultipleCount++;
formData = tformData;
return sinon.spy(tformData, "append");
});
mock1 = getMockFile();
mock2 = getMockFile();
dropzone.addFile(mock1);
dropzone.addFile(mock2);
return setTimeout(function() {
sendingCount.should.equal(2);
sendingMultipleCount.should.equal(1);
dropzone.uploadFiles([mock1, mock2]);
formData.append.callCount.should.equal(2);
formData.append.args[0][0].should.eql("myName[0]");
formData.append.args[1][0].should.eql("myName[1]");
return done();
}, 10);
});
});
return describe("should properly set status of file", function() {
return it("should correctly set `withCredentials` on the xhr object", function(done) {
dropzone.addFile(mockFile);
return setTimeout(function() {
mockFile.status.should.eql(Dropzone.UPLOADING);
requests.length.should.equal(1);
requests[0].status = 400;
requests[0].readyState = 4;
requests[0].onload();
mockFile.status.should.eql(Dropzone.ERROR);
mockFile = getMockFile();
dropzone.addFile(mockFile);
return setTimeout(function() {
mockFile.status.should.eql(Dropzone.UPLOADING);
requests.length.should.equal(2);
requests[1].status = 200;
requests[1].readyState = 4;
requests[1].onload();
mockFile.status.should.eql(Dropzone.SUCCESS);
return done();
}, 10);
}, 10);
});
});
});
return describe("complete file", function() {
return it("should properly emit the queuecomplete event when the complete queue is finished", function(done) {
var completedFiles, mock1, mock2, mock3;
mock1 = getMockFile();
mock2 = getMockFile();
mock3 = getMockFile();
mock1.status = Dropzone.ADDED;
mock2.status = Dropzone.ADDED;
mock3.status = Dropzone.ADDED;
mock1.name = "mock1";
mock2.name = "mock2";
mock3.name = "mock3";
dropzone.uploadFiles = function(files) {
return setTimeout(((function(_this) {
return function() {
return _this._finished(files, null, null);
};
})(this)), 1);
};
completedFiles = 0;
dropzone.on("complete", function(file) {
return completedFiles++;
});
dropzone.on("queuecomplete", function() {
completedFiles.should.equal(3);
return done();
});
dropzone.addFile(mock1);
dropzone.addFile(mock2);
return dropzone.addFile(mock3);
});
});
});
});
}).call(this);
| webfatorial/dropzone | test/test.js | JavaScript | mit | 82,314 |
answer = sum [1..100] ^ 2 - foldl (\x y -> y^2 + x) 0 [1..100]
| tamasgal/haskell_exercises | ProjectEuler/p006.hs | Haskell | mit | 63 |
/**
* generated by Xtext
*/
package dk.itu.smdp.group2.ui.outline;
import org.eclipse.xtext.ui.editor.outline.impl.DefaultOutlineTreeProvider;
/**
* Customization of the default outline structure.
*
* see http://www.eclipse.org/Xtext/documentation.html#outline
*/
@SuppressWarnings("all")
public class QuestionaireOutlineTreeProvider extends DefaultOutlineTreeProvider {
}
| rasmusgreve/questionaire | dk.itu.smdp.group2.questionaire.ui/xtend-gen/dk/itu/smdp/group2/ui/outline/QuestionaireOutlineTreeProvider.java | Java | mit | 382 |
<?php
/*
* ghz.me url shortener
* when a long url hz.
*
* (c) 2014 Sam Thompson <[email protected]>
* License: MIT
*/
define('ROOT_PATH', __DIR__ . '/');
require ROOT_PATH . 'loader.php';
$app = new Ghz\App();
// Handle our two cases:
// - Redirect (when requestiong anything except BASEPATH)
// - Save URL when posted here.
$app->doRedirect();
$app->savePostedUrl();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GHz url shortener</title>
<link rel="stylesheet" href="_assets/style.css">
<?php if (defined('GA_TRACKING')) : ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '<?php echo GA_TRACKING; ?>', 'auto');
ga('send', 'pageview');
</script>
<?php endif; ?>
</head>
<body>
<div class="main">
<h1>
<a href="/">Ghz</a>
</h1>
<p class="subhead">url shortener</p>
<form action="" method="post">
<div class="error<?php if ($app->isFailure()) : ?> visible<?php endif; ?>">
please enter a valid url
</div>
<div class="success<?php if ($app->isSuccess()) : ?> visible<?php endif; ?>">
created!
</div>
<div>
<input placeholder="paste or enter a url and press enter" name="url"
type="text" value="<?php echo $app->getGeneratedUrl(); ?>">
</div>
</form>
</div>
<div class="bottom-left">
© <?php echo date('Y'); ?> Ghz.me
</div>
<div class="bottom-right">
</div>
<!-- fork me banner -->
<a href="https://github.com/samt/ghz">
<img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png">
</a>
<script type="text/javascript" src="_assets/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="_assets/main.js"></script>
</body>
</html>
| samt/ghz | index.php | PHP | mit | 2,503 |
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>module Rack::Mime - 'Rack Documentation'</title>
<link type="text/css" media="screen" href="../rdoc.css" rel="stylesheet">
<script type="text/javascript">
var rdoc_rel_prefix = "../";
</script>
<script type="text/javascript" charset="utf-8" src="../js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/navigation.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/search_index.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/search.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/searcher.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/darkfish.js"></script>
<body id="top" class="module">
<nav id="metadata">
<nav id="home-section" class="section">
<h3 class="section-header">
<a href="../index.html">Home</a>
<a href="../table_of_contents.html#classes">Classes</a>
<a href="../table_of_contents.html#methods">Methods</a>
</h3>
</nav>
<nav id="search-section" class="section project-section" class="initially-hidden">
<form action="#" method="get" accept-charset="utf-8">
<h3 class="section-header">
<input type="text" name="search" placeholder="Search" id="search-field"
title="Type to search, Up and Down to navigate, Enter to load">
</h3>
</form>
<ul id="search-results" class="initially-hidden"></ul>
</nav>
<div id="file-metadata">
<nav id="file-list-section" class="section">
<h3 class="section-header">Defined In</h3>
<ul>
<li>lib/rack/mime.rb
</ul>
</nav>
</div>
<div id="class-metadata">
<!-- Method Quickref -->
<nav id="method-list-section" class="section">
<h3 class="section-header">Methods</h3>
<ul class="link-list">
<li><a href="#method-c-mime_type">::mime_type</a>
</ul>
</nav>
</div>
<div id="project-metadata">
<nav id="fileindex-section" class="section project-section">
<h3 class="section-header">Pages</h3>
<ul>
<li class="file"><a href="../KNOWN-ISSUES.html">KNOWN-ISSUES</a>
<li class="file"><a href="../README_rdoc.html">README</a>
<li class="file"><a href="../SPEC.html">SPEC</a>
</ul>
</nav>
<nav id="classindex-section" class="section project-section">
<h3 class="section-header">Class and Module Index</h3>
<ul class="link-list">
<li><a href="../Rack.html">Rack</a>
<li><a href="../Rack/Auth.html">Rack::Auth</a>
<li><a href="../Rack/Auth/AbstractHandler.html">Rack::Auth::AbstractHandler</a>
<li><a href="../Rack/Auth/AbstractRequest.html">Rack::Auth::AbstractRequest</a>
<li><a href="../Rack/Auth/Basic.html">Rack::Auth::Basic</a>
<li><a href="../Rack/Auth/Basic/Request.html">Rack::Auth::Basic::Request</a>
<li><a href="../Rack/Auth/Digest.html">Rack::Auth::Digest</a>
<li><a href="../Rack/Auth/Digest/MD5.html">Rack::Auth::Digest::MD5</a>
<li><a href="../Rack/Auth/Digest/Nonce.html">Rack::Auth::Digest::Nonce</a>
<li><a href="../Rack/Auth/Digest/Params.html">Rack::Auth::Digest::Params</a>
<li><a href="../Rack/Auth/Digest/Request.html">Rack::Auth::Digest::Request</a>
<li><a href="../Rack/BodyProxy.html">Rack::BodyProxy</a>
<li><a href="../Rack/Builder.html">Rack::Builder</a>
<li><a href="../Rack/Cascade.html">Rack::Cascade</a>
<li><a href="../Rack/Chunked.html">Rack::Chunked</a>
<li><a href="../Rack/Chunked/Body.html">Rack::Chunked::Body</a>
<li><a href="../Rack/CommonLogger.html">Rack::CommonLogger</a>
<li><a href="../Rack/ConditionalGet.html">Rack::ConditionalGet</a>
<li><a href="../Rack/Config.html">Rack::Config</a>
<li><a href="../Rack/ContentLength.html">Rack::ContentLength</a>
<li><a href="../Rack/ContentType.html">Rack::ContentType</a>
<li><a href="../Rack/Deflater.html">Rack::Deflater</a>
<li><a href="../Rack/Deflater/DeflateStream.html">Rack::Deflater::DeflateStream</a>
<li><a href="../Rack/Deflater/GzipStream.html">Rack::Deflater::GzipStream</a>
<li><a href="../Rack/Directory.html">Rack::Directory</a>
<li><a href="../Rack/ETag.html">Rack::ETag</a>
<li><a href="../Rack/File.html">Rack::File</a>
<li><a href="../Rack/ForwardRequest.html">Rack::ForwardRequest</a>
<li><a href="../Rack/Handler.html">Rack::Handler</a>
<li><a href="../Rack/Handler/CGI.html">Rack::Handler::CGI</a>
<li><a href="../Rack/Handler/EventedMongrel.html">Rack::Handler::EventedMongrel</a>
<li><a href="../Rack/Handler/FastCGI.html">Rack::Handler::FastCGI</a>
<li><a href="../Rack/Handler/LSWS.html">Rack::Handler::LSWS</a>
<li><a href="../Rack/Handler/Mongrel.html">Rack::Handler::Mongrel</a>
<li><a href="../Rack/Handler/SCGI.html">Rack::Handler::SCGI</a>
<li><a href="../Rack/Handler/SwiftipliedMongrel.html">Rack::Handler::SwiftipliedMongrel</a>
<li><a href="../Rack/Handler/Thin.html">Rack::Handler::Thin</a>
<li><a href="../Rack/Handler/WEBrick.html">Rack::Handler::WEBrick</a>
<li><a href="../Rack/Head.html">Rack::Head</a>
<li><a href="../Rack/Lint.html">Rack::Lint</a>
<li><a href="../Rack/Lobster.html">Rack::Lobster</a>
<li><a href="../Rack/Lock.html">Rack::Lock</a>
<li><a href="../Rack/Logger.html">Rack::Logger</a>
<li><a href="../Rack/MethodOverride.html">Rack::MethodOverride</a>
<li><a href="../Rack/Mime.html">Rack::Mime</a>
<li><a href="../Rack/MockRequest.html">Rack::MockRequest</a>
<li><a href="../Rack/MockRequest/FatalWarner.html">Rack::MockRequest::FatalWarner</a>
<li><a href="../Rack/MockRequest/FatalWarning.html">Rack::MockRequest::FatalWarning</a>
<li><a href="../Rack/MockResponse.html">Rack::MockResponse</a>
<li><a href="../Rack/Multipart.html">Rack::Multipart</a>
<li><a href="../Rack/Multipart/Generator.html">Rack::Multipart::Generator</a>
<li><a href="../Rack/Multipart/Parser.html">Rack::Multipart::Parser</a>
<li><a href="../Rack/Multipart/UploadedFile.html">Rack::Multipart::UploadedFile</a>
<li><a href="../Rack/NullLogger.html">Rack::NullLogger</a>
<li><a href="../Rack/Recursive.html">Rack::Recursive</a>
<li><a href="../Rack/Reloader.html">Rack::Reloader</a>
<li><a href="../Rack/Reloader/Stat.html">Rack::Reloader::Stat</a>
<li><a href="../Rack/Request.html">Rack::Request</a>
<li><a href="../Rack/Response.html">Rack::Response</a>
<li><a href="../Rack/Response/Helpers.html">Rack::Response::Helpers</a>
<li><a href="../Rack/RewindableInput.html">Rack::RewindableInput</a>
<li><a href="../Rack/RewindableInput/Tempfile.html">Rack::RewindableInput::Tempfile</a>
<li><a href="../Rack/Runtime.html">Rack::Runtime</a>
<li><a href="../Rack/Sendfile.html">Rack::Sendfile</a>
<li><a href="../Rack/Server.html">Rack::Server</a>
<li><a href="../Rack/Server/Options.html">Rack::Server::Options</a>
<li><a href="../Rack/Session.html">Rack::Session</a>
<li><a href="../Rack/Session/Abstract.html">Rack::Session::Abstract</a>
<li><a href="../Rack/Session/Abstract/ID.html">Rack::Session::Abstract::ID</a>
<li><a href="../Rack/Session/Abstract/SessionHash.html">Rack::Session::Abstract::SessionHash</a>
<li><a href="../Rack/Session/Cookie.html">Rack::Session::Cookie</a>
<li><a href="../Rack/Session/Cookie/Base64.html">Rack::Session::Cookie::Base64</a>
<li><a href="../Rack/Session/Cookie/Base64/Marshal.html">Rack::Session::Cookie::Base64::Marshal</a>
<li><a href="../Rack/Session/Cookie/Identity.html">Rack::Session::Cookie::Identity</a>
<li><a href="../Rack/Session/Cookie/Reverse.html">Rack::Session::Cookie::Reverse</a>
<li><a href="../Rack/Session/Memcache.html">Rack::Session::Memcache</a>
<li><a href="../Rack/Session/Pool.html">Rack::Session::Pool</a>
<li><a href="../Rack/ShowExceptions.html">Rack::ShowExceptions</a>
<li><a href="../Rack/ShowStatus.html">Rack::ShowStatus</a>
<li><a href="../Rack/Static.html">Rack::Static</a>
<li><a href="../Rack/URLMap.html">Rack::URLMap</a>
<li><a href="../Rack/Utils.html">Rack::Utils</a>
<li><a href="../Rack/Utils/Context.html">Rack::Utils::Context</a>
<li><a href="../Rack/Utils/HeaderHash.html">Rack::Utils::HeaderHash</a>
<li><a href="../Rack/Multipart.html">Rack::Utils::Multipart</a>
<li><a href="../FCGI.html">FCGI</a>
<li><a href="../FCGI/Stream.html">FCGI::Stream</a>
</ul>
</nav>
</div>
</nav>
<div id="documentation">
<h1 class="module">module Rack::Mime</h1>
<div id="description" class="description">
</div><!-- description -->
<section id="5Buntitled-5D" class="documentation-section">
<!-- Constants -->
<section id="constants-list" class="section">
<h3 class="section-header">Constants</h3>
<dl>
<dt id="MIME_TYPES">MIME_TYPES
<dd class="description"><p>List of most common mime-types, selected various sources according to their
usefulness in a webserving scope for Ruby users.</p>
<p>To amend this list with your local mime.types list you can use:</p>
<pre class="ruby"><span class="ruby-identifier">require</span> <span class="ruby-string">'webrick/httputils'</span>
<span class="ruby-identifier">list</span> = <span class="ruby-constant">WEBrick</span><span class="ruby-operator">::</span><span class="ruby-constant">HTTPUtils</span>.<span class="ruby-identifier">load_mime_types</span>(<span class="ruby-string">'/etc/mime.types'</span>)
<span class="ruby-constant">Rack</span><span class="ruby-operator">::</span><span class="ruby-constant">Mime</span><span class="ruby-operator">::</span><span class="ruby-constant">MIME_TYPES</span>.<span class="ruby-identifier">merge!</span>(<span class="ruby-identifier">list</span>)
</pre>
<p>N.B. On Ubuntu the mime.types file does not include the leading period, so
users may need to modify the data before merging into the hash.</p>
<p>To add the list mongrel provides, use:</p>
<pre class="ruby"><span class="ruby-identifier">require</span> <span class="ruby-string">'mongrel/handlers'</span>
<span class="ruby-constant">Rack</span><span class="ruby-operator">::</span><span class="ruby-constant">Mime</span><span class="ruby-operator">::</span><span class="ruby-constant">MIME_TYPES</span>.<span class="ruby-identifier">merge!</span>(<span class="ruby-constant">Mongrel</span><span class="ruby-operator">::</span><span class="ruby-constant">DirHandler</span><span class="ruby-operator">::</span><span class="ruby-constant">MIME_TYPES</span>)
</pre>
</dl>
</section>
<!-- Methods -->
<section id="public-class-5Buntitled-5D-method-details" class="method-section section">
<h3 class="section-header">Public Class Methods</h3>
<div id="method-c-mime_type" class="method-detail ">
<div class="method-heading">
<span class="method-name">mime_type</span><span
class="method-args">(ext, fallback='application/octet-stream')</span>
<span class="method-click-advice">click to toggle source</span>
</div>
<div class="method-description">
<p>Returns String with mime type if found, otherwise use
<code>fallback</code>. <code>ext</code> should be filename extension in the
‘.ext’ format that</p>
<pre>File.extname(file) returns.</pre>
<p><code>fallback</code> may be any object</p>
<p>Also see the documentation for <a
href="Mime.html#MIME_TYPES">MIME_TYPES</a></p>
<p>Usage:</p>
<pre>Rack::Mime.mime_type('.foo')</pre>
<p>This is a shortcut for:</p>
<pre>Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream')</pre>
<div class="method-source-code" id="mime_type-source">
<pre><span class="ruby-comment"># File lib/rack/mime.rb, line 16</span>
<span class="ruby-keyword">def</span> <span class="ruby-identifier">mime_type</span>(<span class="ruby-identifier">ext</span>, <span class="ruby-identifier">fallback</span>=<span class="ruby-string">'application/octet-stream'</span>)
<span class="ruby-constant">MIME_TYPES</span>.<span class="ruby-identifier">fetch</span>(<span class="ruby-identifier">ext</span>.<span class="ruby-identifier">to_s</span>.<span class="ruby-identifier">downcase</span>, <span class="ruby-identifier">fallback</span>)
<span class="ruby-keyword">end</span></pre>
</div><!-- mime_type-source -->
</div>
</div><!-- mime_type-method -->
</section><!-- public-class-method-details -->
</section><!-- 5Buntitled-5D -->
</div><!-- documentation -->
<footer id="validator-badges">
<p><a href="http://validator.w3.org/check/referer">[Validate]</a>
<p>Generated by <a href="https://github.com/rdoc/rdoc">RDoc</a> 3.12.
<p>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish Rdoc Generator</a> 3.
</footer>
| johnl/deb-ruby-rack | doc/Rack/Mime.html | HTML | mit | 13,266 |
---
layout: page
title: Middleton - Mcdaniel Wedding
date: 2016-05-24
author: Larry Rios
tags: weekly links, java
status: published
summary: Vestibulum ante ipsum primis in faucibus orci luctus et.
banner: images/banner/leisure-02.jpg
booking:
startDate: 02/27/2019
endDate: 03/02/2019
ctyhocn: BROHSHX
groupCode: MMW
published: true
---
Nam at metus eu metus porttitor facilisis interdum id massa. Nulla id diam nec eros fringilla consequat. Nam odio est, commodo sagittis massa ac, dapibus interdum velit. Fusce dignissim pulvinar magna, quis aliquet leo dignissim non. Etiam gravida ullamcorper condimentum. Etiam ut lobortis quam, eu efficitur ante. Etiam posuere vel lorem sed imperdiet.
1 Ut tempus lorem ut ultricies commodo
1 Curabitur eget orci eget diam sodales pretium vitae vitae quam
1 Quisque non metus congue, scelerisque mauris vitae, suscipit dolor
1 Proin tristique justo a urna viverra sagittis.
Aliquam felis lacus, mattis ut sapien nec, bibendum convallis turpis. Donec id nisi lacus. Praesent vehicula bibendum faucibus. Suspendisse sit amet massa vitae mi sodales consequat. Morbi vitae tortor lorem. Donec aliquet ultricies dui, vel convallis dui volutpat a. Praesent finibus, enim nec consequat rutrum, sem felis tincidunt metus, et aliquam lectus leo ullamcorper sem. Cras quis semper erat, sit amet feugiat nunc. Nullam iaculis sodales tellus in pellentesque. Phasellus laoreet gravida quam, quis commodo velit lacinia ut. Donec sodales nibh nec venenatis congue. Maecenas id ultrices mi. Quisque imperdiet sed diam sit amet placerat. Pellentesque pretium nec ante nec rutrum.
Nunc sit amet finibus mauris, vel faucibus sapien. Nunc blandit mi at ante imperdiet, nec aliquam eros egestas. Aliquam sollicitudin neque nisl, et finibus justo placerat non. Maecenas id vestibulum ligula. Morbi efficitur ipsum tortor. Sed ac nunc orci. Donec non eros maximus sapien mollis mollis a id erat.
| KlishGroup/prose-pogs | pogs/B/BROHSHX/MMW/index.md | Markdown | mit | 1,924 |
package wsclient
import (
"github.com/cosminrentea/gobbler/testutil"
"fmt"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/stretchr/testify/assert"
)
var aNormalMessage = `/foo/bar,42,user01,phone01,{},,1420110000,0
Hello World`
var aSendNotification = "#send"
var anErrorNotification = "!error-send"
func MockConnectionFactory(connectionMock *MockWSConnection) func(string, string) (WSConnection, error) {
return func(url string, origin string) (WSConnection, error) {
return connectionMock, nil
}
}
func TestConnectErrorWithoutReconnection(t *testing.T) {
a := assert.New(t)
// given a client
c := New("url", "origin", 1, false)
// which raises an error on connect
callCounter := 0
c.SetWSConnectionFactory(func(url string, origin string) (WSConnection, error) {
a.Equal("url", url)
a.Equal("origin", origin)
callCounter++
return nil, fmt.Errorf("emulate connection error")
})
// when we start
err := c.Start()
// then
a.Error(err)
a.Equal(1, callCounter)
}
func TestConnectErrorWithoutReconnectionUsingOpen(t *testing.T) {
a := assert.New(t)
c, err := Open("url", "origin", 1, false)
// which raises an error on connect
callCounter := 0
c.SetWSConnectionFactory(func(url string, origin string) (WSConnection, error) {
a.Equal("url", url)
a.Equal("origin", origin)
callCounter++
return nil, fmt.Errorf("emulate connection error")
})
a.Error(err)
}
func TestConnectErrorWithReconnection(t *testing.T) {
ctrl, finish := testutil.NewMockCtrl(t)
defer finish()
a := assert.New(t)
// given a client
c := New("url", "origin", 1, true)
// which raises an error twice and then allows to connect
callCounter := 0
connMock := NewMockWSConnection(ctrl)
connMock.EXPECT().ReadMessage().Do(func() { time.Sleep(time.Second) })
c.SetWSConnectionFactory(func(url string, origin string) (WSConnection, error) {
a.Equal("url", url)
a.Equal("origin", origin)
if callCounter <= 2 {
callCounter++
return nil, fmt.Errorf("emulate connection error")
}
return connMock, nil
})
// when we start
err := c.Start()
// then we get an error, first
a.Error(err)
a.False(c.IsConnected())
// when we wait for two iterations and 10ms buffer time to connect
time.Sleep(time.Millisecond * 110)
// then we got connected
a.True(c.IsConnected())
a.Equal(3, callCounter)
}
func TestStopableClient(t *testing.T) {
ctrl, finish := testutil.NewMockCtrl(t)
defer finish()
a := assert.New(t)
// given a client
c := New("url", "origin", 1, true)
// with a closeable connection
connMock := NewMockWSConnection(ctrl)
close := make(chan bool, 1)
connMock.EXPECT().ReadMessage().
Do(func() { <-close }).
Return(0, []byte{}, fmt.Errorf("expected close error"))
connMock.EXPECT().Close().Do(func() {
close <- true
})
c.SetWSConnectionFactory(MockConnectionFactory(connMock))
// when we start
err := c.Start()
// than we are connected
a.NoError(err)
a.True(c.IsConnected())
// when we clode
c.Close()
time.Sleep(time.Millisecond * 1)
// than the client returns
a.False(c.IsConnected())
}
func TestReceiveAMessage(t *testing.T) {
ctrl, finish := testutil.NewMockCtrl(t)
defer finish()
a := assert.New(t)
// given a client
c := New("url", "origin", 10, false)
// with a closeable connection
connMock := NewMockWSConnection(ctrl)
close := make(chan bool, 1)
// normal message
call1 := connMock.EXPECT().ReadMessage().
Return(4, []byte(aNormalMessage), nil)
call2 := connMock.EXPECT().ReadMessage().
Return(4, []byte(aSendNotification), nil)
call3 := connMock.EXPECT().ReadMessage().
Return(4, []byte("---"), nil)
call4 := connMock.EXPECT().ReadMessage().
Return(4, []byte(anErrorNotification), nil)
call5 := connMock.EXPECT().ReadMessage().
Do(func() { <-close }).
Return(0, []byte{}, fmt.Errorf("expected close error")).
AnyTimes()
call5.After(call4)
call4.After(call3)
call3.After(call2)
call2.After(call1)
c.SetWSConnectionFactory(MockConnectionFactory(connMock))
connMock.EXPECT().Close().Do(func() {
close <- true
})
// when we start
err := c.Start()
a.NoError(err)
a.True(c.IsConnected())
// than we receive the expected message
select {
case m := <-c.Messages():
a.Equal(aNormalMessage, string(m.Encode()))
case <-time.After(time.Millisecond * 10):
a.Fail("timeout while waiting for message")
}
// and we receive the notification
select {
case m := <-c.StatusMessages():
a.Equal(aSendNotification, string(m.Bytes()))
case <-time.After(time.Millisecond * 10):
a.Fail("timeout while waiting for message")
}
// parse error
select {
case m := <-c.Errors():
a.True(strings.HasPrefix(string(m.Bytes()), "!clientError "))
case <-time.After(time.Millisecond * 10):
a.Fail("timeout while waiting for message")
}
// and we receive the error notification
select {
case m := <-c.Errors():
a.Equal(anErrorNotification, string(m.Bytes()))
case <-time.After(time.Millisecond * 10):
a.Fail("timeout while waiting for message")
}
c.Close()
}
func TestSendAMessage(t *testing.T) {
ctrl, finish := testutil.NewMockCtrl(t)
defer finish()
// a := assert.New(t)
// given a client
c := New("url", "origin", 1, true)
// when expects a message
connMock := NewMockWSConnection(ctrl)
connMock.EXPECT().WriteMessage(websocket.BinaryMessage, []byte("> /foo\n{}\nTest"))
connMock.EXPECT().
ReadMessage().
Return(websocket.BinaryMessage, []byte(aNormalMessage), nil).
Do(func() {
time.Sleep(time.Millisecond * 50)
}).
AnyTimes()
c.SetWSConnectionFactory(MockConnectionFactory(connMock))
c.Start()
// then the expectation is meet by sending it
c.Send("/foo", "Test", "{}")
// stop client after 200ms
time.AfterFunc(time.Millisecond*200, func() { c.Close() })
}
func TestSendSubscribeMessage(t *testing.T) {
ctrl, finish := testutil.NewMockCtrl(t)
defer finish()
// given a client
c := New("url", "origin", 1, true)
// when expects a message
connMock := NewMockWSConnection(ctrl)
connMock.EXPECT().WriteMessage(websocket.BinaryMessage, []byte("+ /foo"))
connMock.EXPECT().
ReadMessage().
Return(websocket.BinaryMessage, []byte(aNormalMessage), nil).
Do(func() {
time.Sleep(time.Millisecond * 50)
}).
AnyTimes()
c.SetWSConnectionFactory(MockConnectionFactory(connMock))
c.Start()
c.Subscribe("/foo")
// stop client after 200ms
time.AfterFunc(time.Millisecond*200, func() { c.Close() })
}
func TestSendUnSubscribeMessage(t *testing.T) {
ctrl, finish := testutil.NewMockCtrl(t)
defer finish()
// given a client
c := New("url", "origin", 1, true)
// when expects a message
connMock := NewMockWSConnection(ctrl)
connMock.EXPECT().WriteMessage(websocket.BinaryMessage, []byte("- /foo"))
connMock.EXPECT().
ReadMessage().
Return(websocket.BinaryMessage, []byte(aNormalMessage), nil).
Do(func() {
time.Sleep(time.Millisecond * 50)
}).
AnyTimes()
c.SetWSConnectionFactory(MockConnectionFactory(connMock))
c.Start()
c.Unsubscribe("/foo")
// stop client after 200ms
time.AfterFunc(time.Millisecond*200, func() { c.Close() })
}
| cosminrentea/gobbler | client/wsclient/client_test.go | GO | mit | 7,087 |
namespace LadderLogic.Controller.State
{
using Surface;
public class CursorState : State
{
public CursorState () : base(StateType.CursorState)
{
}
#region implemented abstract members of State
public override bool Handle (State previous, Segment prevSegment, Segment newSegment, bool left)
{
base.Handle (previous, prevSegment, newSegment, left);
return true;
}
#endregion
}
}
| cpipero/ArduinoLadder | Controller/State/CursorState.cs | C# | mit | 411 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_12_01
module Models
#
# A load balancer probe.
#
class Probe < SubResource
include MsRestAzure
# @return [Array<SubResource>] The load balancer rules that use this
# probe.
attr_accessor :load_balancing_rules
# @return [ProbeProtocol] The protocol of the end point. If 'Tcp' is
# specified, a received ACK is required for the probe to be successful.
# If 'Http' or 'Https' is specified, a 200 OK response from the specifies
# URI is required for the probe to be successful. Possible values
# include: 'Http', 'Tcp', 'Https'
attr_accessor :protocol
# @return [Integer] The port for communicating the probe. Possible values
# range from 1 to 65535, inclusive.
attr_accessor :port
# @return [Integer] The interval, in seconds, for how frequently to probe
# the endpoint for health status. Typically, the interval is slightly
# less than half the allocated timeout period (in seconds) which allows
# two full probes before taking the instance out of rotation. The default
# value is 15, the minimum value is 5.
attr_accessor :interval_in_seconds
# @return [Integer] The number of probes where if no response, will
# result in stopping further traffic from being delivered to the
# endpoint. This values allows endpoints to be taken out of rotation
# faster or slower than the typical times used in Azure.
attr_accessor :number_of_probes
# @return [String] The URI used for requesting health status from the VM.
# Path is required if a protocol is set to http. Otherwise, it is not
# allowed. There is no default value.
attr_accessor :request_path
# @return [ProvisioningState] The provisioning state of the probe
# resource. Possible values include: 'Succeeded', 'Updating', 'Deleting',
# 'Failed'
attr_accessor :provisioning_state
# @return [String] The name of the resource that is unique within the set
# of probes used by the load balancer. This name can be used to access
# the resource.
attr_accessor :name
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
# @return [String] Type of the resource.
attr_accessor :type
#
# Mapper for Probe class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Probe',
type: {
name: 'Composite',
class_name: 'Probe',
model_properties: {
id: {
client_side_validation: true,
required: false,
serialized_name: 'id',
type: {
name: 'String'
}
},
load_balancing_rules: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.loadBalancingRules',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'SubResourceElementType',
type: {
name: 'Composite',
class_name: 'SubResource'
}
}
}
},
protocol: {
client_side_validation: true,
required: true,
serialized_name: 'properties.protocol',
type: {
name: 'String'
}
},
port: {
client_side_validation: true,
required: true,
serialized_name: 'properties.port',
type: {
name: 'Number'
}
},
interval_in_seconds: {
client_side_validation: true,
required: false,
serialized_name: 'properties.intervalInSeconds',
type: {
name: 'Number'
}
},
number_of_probes: {
client_side_validation: true,
required: false,
serialized_name: 'properties.numberOfProbes',
type: {
name: 'Number'
}
},
request_path: {
client_side_validation: true,
required: false,
serialized_name: 'properties.requestPath',
type: {
name: 'String'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'etag',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2019-12-01/generated/azure_mgmt_network/models/probe.rb | Ruby | mit | 6,258 |
#pragma once
#include <mime/mimepp/mimepp.h>
namespace Zimbra
{
namespace MAPI
{
#define PR_URL_NAME PROP_TAG(PT_TSTRING, 0x6707)
#define EXCHIVERB_OPEN 0
#define EXCHIVERB_RESERVED_COMPOSE 100
#define EXCHIVERB_RESERVED_OPEN 101
#define EXCHIVERB_REPLYTOSENDER 102
#define EXCHIVERB_REPLYTOALL 103
#define EXCHIVERB_FORWARD 104
#define EXCHIVERB_PRINT 105
#define EXCHIVERB_SAVEAS 106
#define EXCHIVERB_RESERVED_DELIVERY 107
#define EXCHIVERB_REPLYTOFOLDER 108
typedef enum _ZM_ITEM_TYPE
{
ZT_NONE = 0, ZT_MAIL, ZT_CONTACTS, ZT_APPOINTMENTS, ZT_TASKS, ZT_MEETREQ, ZTMAX
} ZM_ITEM_TYPE;
// MAPIMessageException class
class MAPIMessageException: public GenericException
{
public:
MAPIMessageException(HRESULT hrErrCode, LPCWSTR lpszDescription);
MAPIMessageException(HRESULT hrErrCode, LPCWSTR lpszDescription, LPCWSTR lpszShortDescription, int nLine, LPCSTR strFile);
virtual ~MAPIMessageException() {}
};
// MAPIMessage Class
class MAPIMessage
{
private:
// order of the message properties in _pMessagePropVals
typedef enum _MessagePropIndex
{
MESSAGE_CLASS, MESSAGE_FLAGS, MESSAGE_DATE, SENDER_ADDRTYPE, SENDER_EMAIL_ADDR,
SENDER_NAME, SENDER_ENTRYID, SUBJECT, TEXT_BODY, HTML_BODY, INTERNET_CPID,
MESSAGE_CODEPAGE, LAST_VERB_EXECUTED, FLAG_STATUS, ENTRYID, SENT_ADDRTYPE,
SENT_ENTRYID, SENT_EMAIL_ADDR, SENT_NAME, REPLY_NAMES, REPLY_ENTRIES,
MIME_HEADERS, IMPORTANCE, INTERNET_MESSAGE_ID, DELIVERY_DATE, URL_NAME,
MESSAGE_SIZE, STORE_SUPPORT_MASK, RTF_IN_SYNC, NMSGPROPS
} MessagePropIndex;
// defined so a static variable can hold the message props to retrieve
typedef struct _MessagePropTags
{
ULONG cValues;
ULONG aulPropTags[NMSGPROPS];
} MessagePropTags;
// order of the recipient properties in each row of _pRecipRows
typedef enum _RecipientPropIndex
{
RDISPLAY_NAME, RENTRYID, RADDRTYPE, REMAIL_ADDRESS, RRECIPIENT_TYPE, RNPROPS
} RecipientPropIndex;
// defined so a static variable can hold the recipient properties to retrieve
typedef struct _RecipientPropTags
{
ULONG cValues;
ULONG aulPropTags[RNPROPS];
} RecipientPropTags;
// order of the recipient properties in each row of _pRecipRows
typedef enum _ReplyToPropIndex
{
REPLYTO_DISPLAY_NAME, REPLYTO_ENTRYID, REPLYTO_ADDRTYPE, REPLYTO_EMAIL_ADDRESS,
NREPLYTOPROPS
} ReplyToPropIndex;
// defined so a static variable can hold the recipient properties to retrieve
typedef struct _ReplyToPropTags
{
ULONG cValues;
ULONG aulPropTags[NREPLYTOPROPS];
} ReplyToPropTags;
MAPISession *m_session;
LPMESSAGE m_pMessage;
LPSPropValue m_pMessagePropVals;
LPSRowSet m_pRecipientRows;
SBinary m_EntryID;
CHAR m_pDateTimeStr[32];
CHAR m_pDeliveryDateTimeStr[32];
CHAR m_pDeliveryUnixDateTimeStr[32];
std::vector<std::string> RTFElement;
enum EnumRTFElement
{
NOTFOUND = -1, OPENBRACE = 0, CLOSEBRACE, HTMLTAG, MHTMLTAG, PAR, TAB, LI, FI, HEXCHAR,
PNTEXT, HTMLRTF, OPENBRACEESC, CLOSEBRACEESC, END, HTMLRTF0
};
static MessagePropTags m_messagePropTags;
static RecipientPropTags m_recipientPropTags;
static ReplyToPropTags m_replyToPropTags;
unsigned int CodePageId();
EnumRTFElement MatchRTFElement(const char *psz);
const char *Advance(const char *psz, const char *pszCharSet);
public:
MAPIMessage();
~MAPIMessage();
void Initialize(LPMESSAGE pMessage, MAPISession &session, bool bPartial=false);
void InternalFree();
LPMESSAGE InternalMessageObject() { return m_pMessage; }
bool Subject(LPTSTR *ppSubject);
ZM_ITEM_TYPE ItemType();
bool IsFlagged();
bool GetURLName(LPTSTR *pstrUrlName);
bool IsDraft();
BOOL IsFromMe();
BOOL IsUnread();
BOOL Forwarded();
BOOL RepliedTo();
bool HasAttach();
BOOL IsUnsent();
bool HasHtmlPart();
bool HasTextPart();
SBinary &UniqueId();
__int64 DeliveryDate();
LPSTR DateString();
__int64 Date();
DWORD Size();
LPSTR DeliveryDateString();
LPSTR DeliveryUnixString();
std::vector<LPWSTR>* SetKeywords();
SBinary EntryID() { return m_EntryID; }
bool TextBody(LPTSTR *ppBody, unsigned int &nTextChars);
// reads the utf8 body and retruns it with accented chararcters
bool UTF8EncBody(LPTSTR *ppBody, unsigned int &nTextChars);
// return the html body of the message
bool HtmlBody(LPVOID *ppBody, unsigned int &nHtmlBodyLen);
bool DecodeRTF2HTML(char *buf, unsigned int *len);
bool IsRTFHTML(const char *buf);
void ToMimePPMessage(mimepp::Message &msg);
};
class MIRestriction;
// Message Iterator class
class MessageIterator: public MAPITableIterator
{
private:
typedef enum _MessageIterPropTagIdx
{
MI_ENTRYID, MI_LONGTERM_ENTRYID_FROM_TABLE, MI_DATE, MI_MESSAGE_CLASS, NMSGPROPS
} MessageIterPropTagIdx;
typedef struct _MessageIterPropTags
{
ULONG cValues;
ULONG aulPropTags[NMSGPROPS];
} MessageIterPropTags;
typedef struct _MessageIterSort
{
ULONG cSorts;
ULONG cCategories;
ULONG cExpanded;
SSortOrder aSort[1];
} MessageIterSortOrder;
public:
MessageIterator();
virtual ~MessageIterator();
virtual LPSPropTagArray GetProps();
virtual LPSSortOrderSet GetSortOrder();
virtual LPSRestriction GetRestriction(ULONG TypeMask, FILETIME startDate);
BOOL GetNext(MAPIMessage &msg);
BOOL GetNext(__int64 &date, SBinary &bin);
protected:
static MessageIterPropTags m_props;
static MessageIterSortOrder m_sortOrder;
static MIRestriction m_restriction;
};
// Restriction class
class MIRestriction
{
public:
MIRestriction();
~MIRestriction();
LPSRestriction GetRestriction(ULONG TypeMask, FILETIME startDate);
private:
SRestriction pR[25];
SPropValue _propValCont;
SPropValue _propValMail;
SPropValue _propValCTime;
SPropValue _propValSTime;
SPropValue _propValCanbeMail;
SPropValue _propValCanbeMailPost;
SPropValue _propValAppt;
LPWSTR _pApptClass;
SPropValue _propValTask;
LPWSTR _pTaskClass;
SPropValue _propValReqAndRes;
LPWSTR _pReqAndResClass;
SPropValue _propValDistList;
LPWSTR _pDistListClass;
LPWSTR _pContactClass;
LPWSTR _pMailClass;
SPropValue _propValIMAPHeaderOnly;
};
mimepp::Mailbox *MakeMimePPMailbox(LPTSTR pDisplayName, LPTSTR pSmtpAddress);
}
}
| nico01f/z-pec | ZimbraMigrationTools/src/c/Exchange/MAPIMessage.h | C | mit | 6,675 |
<?php
namespace Juice\UploadBundle\Form\Type;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class BaseFileType extends AbstractUploadType
{
public function buildView(FormView $view, FormInterface $form, array $options)
{
$this->addVars($view, $options);
}
public function getName()
{
return 'juice_upload_file_type';
}
} | dakkor71/UploadBundle | Form/Type/BaseFileType.php | PHP | mit | 462 |
<html>
<head>
<meta http-equiv="refresh" content="0; url=https://minecrafthopper.net/">
<link rel="canonical" href="https://minecrafthopper.net/"/>
</head>
</html>
| MinecraftIRC/MinecraftIRC.net | hopper/index.html | HTML | mit | 172 |
<?php
namespace TFE\LibrairieBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class AccompagnementModifierType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {}
/**
* @return string
*/
public function getName()
{
return 'tfe_librairiebundle_accompagnement_modifier';
}
/**
* @return AccompagnementType
*/
public function getParent()
{
return new AccompagnementType();
}
}
| durandludovic/tfe | src/TFE/LibrairieBundle/Form/AccompagnementModifierType.php | PHP | mit | 647 |
using Dufry.Comissoes.Domain.Validation;
namespace Dufry.Comissoes.Domain.Interfaces.Validation
{
public interface IValidation<in TEntity>
{
ValidationResult Valid(TEntity entity);
}
} | robertohermes/Comissoes | Dufry.Comissoes.Domain/Interfaces/Validation/IValidation.cs | C# | mit | 208 |
import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable, ReplaySubject, throwError} from 'rxjs';
import {map, tap, switchMap} from 'rxjs/operators';
import {SocketService} from './sockets';
import {StorageService} from './storage';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private session: string;
private userInfo: any;
private authEvents: ReplaySubject<{User: any, Session: string}>;
constructor(
private _http: HttpClient,
private _storage: StorageService,
private _sockets: SocketService,
) {
this.authEvents = new ReplaySubject<{User: any, Session: string}>(1);
}
private nuke() {
this._storage.clear();
this.session = undefined;
this.userInfo = undefined;
this._sockets.leave();
}
getSession() {
return this.session;
}
getUser() {
return this.userInfo;
}
hasAccess(): boolean {
return !!this.userInfo;
}
observe(): Observable<{User: any, Session: string}> {
return this.authEvents;
}
identify() {
this._http.get<{Data: any}>(`/api/auth/`)
.pipe(
map(res => res.Data)
)
.subscribe(
data => {
this.session = data.Session.Key;
this.userInfo = data.User;
this._sockets.join(data.Session.Key);
this.authEvents.next({User: data.User, Session: data.Session.Key});
},
err => console.error(err)
);
}
logIn(creds): Observable<any> {
if (!creds || !creds.Username || !creds.Password) {
return throwError('Need login creds');
}
return this._http.post<{Data: any}>('/api/login', creds)
.pipe(
map(res => res.Data),
tap(data => {
this.session = data.Session;
this.userInfo = data.User;
this._sockets.join(data.Session);
this.authEvents.next(data);
})
);
}
signUp(creds): Observable<any> {
if (!creds || !creds.Username || !creds.Email || !creds.Password) {
return throwError('Need signup creds');
}
return this._http.post('/api/signup', creds, {responseType: 'text' as 'text'})
.pipe(
switchMap(_ => this.logIn(creds))
);
}
expireSocket() {
this.userInfo = null;
this.session = null;
this.authEvents.next(null);
}
logOut(): Observable<any> {
return this._http.post('/api/logOut', null)
.pipe(
tap(
res => this.nuke(),
err => this.nuke(),
() => this.authEvents.next(null)
)
);
}
}
| swimmadude66/YTRadio | src/client/services/auth.ts | TypeScript | mit | 2,997 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module DirectoryAPI.API
( directoryAPIProxy
, DirectoryAPI
) where
import Servant
import AuthAPI.API (AuthToken)
import Models (File, Node, NodeId)
type DirectoryAPI = "ls" :> -- List all files
AuthToken :>
Get '[JSON] [File] -- Listing of all files
:<|> "whereis" :> -- Lookup the node for a given file path
AuthToken :>
ReqBody '[JSON] FilePath :> -- Path of file being looked up
Post '[JSON] Node -- Node where the file is kept
:<|> "roundRobinNode" :> -- Next node to use as a file primary
AuthToken :>
ReqBody '[JSON] FilePath :> -- Path of file that will be written
Get '[JSON] Node -- Primary node of the file being stored
:<|> "registerFileServer" :> -- Register a node with the directory service
ReqBody '[JSON] Int :> -- Port file server node is running on
Post '[JSON] NodeId -- Id of the newly created node record
directoryAPIProxy :: Proxy DirectoryAPI
directoryAPIProxy = Proxy
| houli/distributed-file-system | dfs-shared/src/DirectoryAPI/API.hs | Haskell | mit | 1,213 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="jquery/jquery-1.8.1.js"></script>
<script src="jquery/jquery-ui-1.10.3.custom.js"></script>
<script src="treema/tv4.js"></script>
<script src="treema/treema.js"></script>
<link href="jquery/jquery-ui-1.10.3.custom.css" rel="stylesheet">
<link href="treema/treema.css" rel="stylesheet">
</head>
<body>
<div id="addresses"></div>
<script>
var contacts = [
{ 'street-address': '10 Downing Street', 'country-name': 'UK', 'locality': 'London', 'name': 'Prime Minister' },
{ 'street-address': '1600 Amphitheatre Pkwy', 'phone-number': '(650) 253-0000', 'name': 'Google'},
{ 'street-address': '45 Rockefeller Plaza', 'region': 'NY', 'locality': 'New York', 'name': 'Rockefeller Center'},
];
var contact_book_schema = {
type: 'array',
items: {
"additionalProperties": false,
"type": "object",
"displayProperty": 'name',
"properties": {
"name": { type: "string", maxLength: 20 },
"street-address": { title: "Address 1", description: "Don't forget the number.", type: "string" },
"locality":{ "type": "string", title: "Locality" },
"region": { 'title': 'Region', type: 'string' },
"country-name": { "type": "string", title: "Country" },
"friend": { "type": "boolean", title: "Friend" },
"phone-number": { type: "string", maxLength: 20, minLength:4, title: 'Phone Number' }
}
}
};
//buildTreemaExample($('#addresses'), contact_book_schema, contacts);
var treema = $('#addresses').treema({schema: contact_book_schema, data: contacts});
treema.build();
</script>
</body>
</html>
| kub1x/sowl | sample-treema/data/treema.html | HTML | mit | 1,755 |
package com.lightspeedhq.ecom;
import com.lightspeedhq.ecom.domain.LightspeedEComError;
import feign.FeignException;
import lombok.Getter;
/**
*
* @author stevensnoeijen
*/
public class LightspeedEComErrorException extends FeignException {
@Getter
private LightspeedEComError error;
public LightspeedEComErrorException(String message, LightspeedEComError error) {
super(message);
this.error = error;
}
@Override
public String toString() {
return error.toString();
}
}
| Falkplan/lightspeedecom-api | lightspeedecom-api/src/main/java/com/lightspeedhq/ecom/LightspeedEComErrorException.java | Java | mit | 528 |
edit-movie
==========
Script to edit Star Wars with ffmpeg to make it a bit more child-friendly
| davehampson/edit-movie | README.md | Markdown | mit | 97 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="eu_ES" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About POPCoin</source>
<translation>POPCoin-i buruz</translation>
</message>
<message>
<location line="+39"/>
<source><b>POPCoin</b> version</source>
<translation><b>POPCoin</b> bertsioa</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>POPCoin</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Helbide-liburua</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Klik bikoitza helbidea edo etiketa editatzeko</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Sortu helbide berria</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopiatu hautatutako helbidea sistemaren arbelera</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your POPCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Erakutsi &QR kodea</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a POPCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified POPCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Ezabatu</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your POPCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Esportatu Helbide-liburuaren datuak</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Komaz bereizitako artxiboa (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Errorea esportatzean</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ezin idatzi %1 artxiboan.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiketa</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Helbidea</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(etiketarik ez)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Sartu pasahitza</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Pasahitz berria</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Errepikatu pasahitz berria</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Sartu zorrorako pasahitz berria.<br/> Mesedez erabili <b>gutxienez ausazko 10 karaktere</b>, edo <b>gutxienez zortzi hitz</b> pasahitza osatzeko.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Enkriptatu zorroa</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Eragiketa honek zorroaren pasahitza behar du zorroa desblokeatzeko.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desblokeatu zorroa</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Eragiketa honek zure zorroaren pasahitza behar du, zorroa desenkriptatzeko.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Desenkriptatu zorroa</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Aldatu pasahitza</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Sartu zorroaren pasahitz zaharra eta berria.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Berretsi zorroaren enkriptazioa</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR POPCOIN</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Zorroa enkriptatuta</translation>
</message>
<message>
<location line="-56"/>
<source>POPCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your popcoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Zorroaren enkriptazioak huts egin du</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Zorroaren enkriptazioak huts egin du barne-errore baten ondorioz. Zure zorroa ez da enkriptatu.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Eman dituzun pasahitzak ez datoz bat.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Zorroaren desblokeoak huts egin du</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Zorroa desenkriptatzeko sartutako pasahitza okerra da.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Zorroaren desenkriptazioak huts egin du</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sarearekin sinkronizatzen...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Gainbegiratu</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Ikusi zorroaren begirada orokorra</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transakzioak</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Ikusi transakzioen historia</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Editatu gordetako helbide eta etiketen zerrenda</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Erakutsi ordainketak jasotzeko helbideen zerrenda</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>Irten</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Irten aplikaziotik</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about POPCoin</source>
<translation>Erakutsi POPCoin-i buruzko informazioa</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>&Qt-ari buruz</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Erakutsi POPCoin-i buruzko informazioa</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Aukerak...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a POPCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for POPCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Aldatu zorroa enkriptatzeko erabilitako pasahitza</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>POPCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About POPCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your POPCoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified POPCoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Artxiboa</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Ezarpenak</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Laguntza</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Fitxen tresna-barra</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>POPCoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to POPCoin network</source>
<translation><numerusform>Konexio aktibo %n POPCoin-en sarera</numerusform><numerusform>%n konexio aktibo POPCoin-en sarera</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Egunean</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Eguneratzen...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Bidalitako transakzioa</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Sarrerako transakzioa</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid POPCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Zorroa <b>enkriptatuta</b> eta <b>desblokeatuta</b> dago une honetan</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Zorroa <b>enkriptatuta</b> eta <b>blokeatuta</b> dago une honetan</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. POPCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editatu helbidea</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiketa</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Helbide-liburuko sarrera honekin lotutako etiketa</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Helbidea</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Helbide-liburuko sarrera honekin lotutako helbidea. Bidaltzeko helbideeta soilik alda daiteke.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Jasotzeko helbide berria</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Bidaltzeko helbide berria</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editatu jasotzeko helbidea</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editatu bidaltzeko helbidea</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Sartu berri den helbidea, "%1", helbide-liburuan dago jadanik.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid POPCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Ezin desblokeatu zorroa.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Gako berriaren sorrerak huts egin du.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>POPCoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Aukerak</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start POPCoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start POPCoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the POPCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the POPCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting POPCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show POPCoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting POPCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Inprimakia</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the POPCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldoa:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Konfirmatu gabe:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Azken transakzioak</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Zure uneko saldoa</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Oraindik konfirmatu gabe daudenez, uneko saldoab kontatu gabe dagoen transakzio kopurua</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start popcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Kopurua</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>&Etiketa:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mezua</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>Gorde honela...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the POPCoin-Qt help message to get a list with possible POPCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>POPCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>POPCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the POPCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the POPCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Bidali txanponak</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Bidali hainbat jasotzaileri batera</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldoa:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Berretsi bidaltzeko ekintza</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> honi: %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Berretsi txanponak bidaltzea</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Ziur zaude %1 bidali nahi duzula?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>eta</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Ordaintzeko kopurua 0 baino handiagoa izan behar du.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Inprimakia</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>K&opurua:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Ordaindu &honi:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Sartu etiketa bat helbide honetarako, eta gehitu zure helbide-liburuan</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiketa:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Itsatsi helbidea arbeletik</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Ezabatu jasotzaile hau</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a POPCoin address (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source>
<translation>Sartu Bitocin helbide bat (adb.: sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK) </translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Itsatsi helbidea arbeletik</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this POPCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified POPCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a POPCoin address (e.g. sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK)</source>
<translation>Sartu Bitocin helbide bat (adb.: sSxjmkQbhzcbnhNLPru6TwPy4HRPogaDcK) </translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter POPCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>POPCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Zabalik %1 arte</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/konfirmatu gabe</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 konfirmazioak</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Kopurua</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ez da arrakastaz emititu oraindik</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>ezezaguna</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transakzioaren xehetasunak</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Panel honek transakzioaren deskribapen xehea erakusten du</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Mota</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Helbidea</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Kopurua</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Zabalik %1 arte</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 konfirmazio)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Konfirmatuta (%1 konfirmazio)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Bloke hau ez du beste inongo nodorik jaso, eta seguruenik ez da onartuko!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Sortua, baina ez onartua</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Jasoa honekin: </translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Honi bidalia: </translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Ordainketa zeure buruari</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Bildua</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transakzioaren egoera. Pasatu sagua gainetik konfirmazio kopurua ikusteko.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Transakzioa jasotako data eta ordua.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Transakzio mota.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Transakzioaren xede-helbidea.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Saldoan kendu edo gehitutako kopurua.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Denak</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Gaur</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Aste honetan</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Hil honetan</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Azken hilean</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Aurten</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Muga...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Jasota honekin: </translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Hona bidalia: </translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Zeure buruari</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Bildua</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Beste</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Sartu bilatzeko helbide edo etiketa</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Kopuru minimoa</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopiatu helbidea</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopiatu etiketa</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Transakzioaren xehetasunak</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Komaz bereizitako artxiboa (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Mota</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiketa</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Helbidea</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Kopurua</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Errorea esportatzean</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ezin idatzi %1 artxiboan.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>POPCoin version</source>
<translation>Botcoin bertsioa</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or popcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Komandoen lista</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Laguntza komando batean</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Aukerak</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: popcoin.conf)</source>
<translation>Ezarpen fitxategia aukeratu (berezkoa: popcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: popcoind.pid)</source>
<translation>pid fitxategia aukeratu (berezkoa: popcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9247 or testnet: 19247)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9347 or testnet: 19347)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=popcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "POPCoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. POPCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong POPCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the POPCoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Laguntza mezu hau</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of POPCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart POPCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. POPCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Birbilatzen...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Zamaketa amaitua</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | popcointeam/popcoin | src/qt/locale/bitcoin_eu_ES.ts | TypeScript | mit | 99,892 |
<?php
namespace ZpgRtf\Tests\Objects;
use PHPUnit\Framework\TestCase;
use ZpgRtf\Objects\EpcRatingsObject;
class EpcRatingsObjectTest extends TestCase
{
/**
* @var EpcRatingsObject
*/
protected $object;
public function setUp()
{
$this->object = new EpcRatingsObject();
}
public function testCanInstantiate()
{
$this->assertInstanceOf(
EpcRatingsObject::class,
$this->object
);
}
public function testCanSetEerCurrentRating()
{
$this->assertInstanceOf(
EpcRatingsObject::class,
$this->object->setEerCurrentRating(80)
);
$this->assertSame(
80,
$this->object->getEerCurrentRating()
);
}
public function testCanSetEerPotentialRating()
{
$this->assertInstanceOf(
EpcRatingsObject::class,
$this->object->setEerPotentialRating(95)
);
$this->assertSame(
95,
$this->object->getEerPotentialRating()
);
}
public function testCanSetEirCurrentRating()
{
$this->assertInstanceOf(
EpcRatingsObject::class,
$this->object->setEirCurrentRating(50)
);
$this->assertSame(
50,
$this->object->getEirCurrentRating()
);
}
public function testCanSetEirPotentialRating()
{
$this->assertInstanceOf(
EpcRatingsObject::class,
$this->object->setEirPotentialRating(100)
);
$this->assertSame(
100,
$this->object->getEirPotentialRating()
);
}
public function testCanJsonSerialize()
{
$this->assertJson(
json_encode($this->object)
);
$this->assertInstanceOf(
\JsonSerializable::class,
$this->object
);
}
}
| lukeoliff/zpg-rtf-php | tests/Objects/EpcRatingsObjectTest.php | PHP | mit | 1,924 |
import sys
tagging_filepath = sys.argv[1]
following_filepath = sys.argv[2]
delim = '\t'
if len(sys.argv) > 3:
delim = sys.argv[3]
graph = {}
for line in open(tagging_filepath):
entry = line.rstrip().split('\t')
src = entry[0]
dst = entry[1]
if not src in graph: graph[src] = {}
graph[src][dst] = 0
for line in open(following_filepath):
entry = line.rstrip().split('\t')
src = entry[0]
dst = entry[1]
if src in graph and dst in graph[src]:
graph[src][dst] += 1
if dst in graph and src in graph[dst]:
graph[dst][src] += 2
w_dir = 0
wo_dir = 0
count = 0.0
for src in graph:
for dst in graph[src]:
val = graph[src][dst]
count += 1
if val in [1,3]:
w_dir += 1
if val in [1,2,3]:
wo_dir += 1
print "%s\t%s" % (w_dir/count, wo_dir/count)
| yamaguchiyuto/icwsm15 | tag_follow_disagreement.py | Python | mit | 857 |
/* Copyright (c) 2014-2020, The Tor Project, Inc. */
/* See LICENSE for licensing information */
#include "core/or/or.h"
#ifndef TOR_LOG_TEST_HELPERS_H
#define TOR_LOG_TEST_HELPERS_H
/** An element of mock_saved_logs(); records the log element that we
* received. */
typedef struct mock_saved_log_entry_t {
int severity;
const char *funcname;
const char *suffix;
const char *format;
char *generated_msg;
} mock_saved_log_entry_t;
void mock_clean_saved_logs(void);
const smartlist_t *mock_saved_logs(void);
void setup_capture_of_logs(int new_level);
void setup_full_capture_of_logs(int new_level);
void teardown_capture_of_logs(void);
int mock_saved_log_has_message(const char *msg);
int mock_saved_log_has_message_containing(const char *msg);
int mock_saved_log_has_message_not_containing(const char *msg);
int mock_saved_log_has_severity(int severity);
int mock_saved_log_has_entry(void);
int mock_saved_log_n_entries(void);
void mock_dump_saved_logs(void);
#define assert_log_predicate(predicate, failure_msg) \
do { \
if (!(predicate)) { \
TT_FAIL(failure_msg); \
mock_dump_saved_logs(); \
TT_EXIT_TEST_FUNCTION; \
} \
} while (0)
#define expect_log_msg(str) \
assert_log_predicate(mock_saved_log_has_message(str), \
("expected log to contain \"%s\"", str));
#define expect_log_msg_containing(str) \
assert_log_predicate(mock_saved_log_has_message_containing(str), \
("expected log to contain \"%s\"", str));
#define expect_log_msg_not_containing(str) \
assert_log_predicate(mock_saved_log_has_message_not_containing(str), \
("expected log to not contain \"%s\"", str));
#define expect_log_msg_containing_either(str1, str2) \
assert_log_predicate(mock_saved_log_has_message_containing(str1) || \
mock_saved_log_has_message_containing(str2), \
("expected log to contain \"%s\" or \"%s\"", str1, str2));
#define expect_log_msg_containing_either3(str1, str2, str3) \
assert_log_predicate(mock_saved_log_has_message_containing(str1) || \
mock_saved_log_has_message_containing(str2) || \
mock_saved_log_has_message_containing(str3), \
("expected log to contain \"%s\" or \"%s\" or \"%s\"", \
str1, str2, str3))
#define expect_log_msg_containing_either4(str1, str2, str3, str4) \
assert_log_predicate(mock_saved_log_has_message_containing(str1) || \
mock_saved_log_has_message_containing(str2) || \
mock_saved_log_has_message_containing(str3) || \
mock_saved_log_has_message_containing(str4), \
("expected log to contain \"%s\" or \"%s\" or \"%s\" or \"%s\"", \
str1, str2, str3, str4))
#define expect_single_log_msg(str) \
do { \
\
assert_log_predicate(mock_saved_log_has_message_containing(str) && \
mock_saved_log_n_entries() == 1, \
("expected log to contain exactly 1 message \"%s\"", \
str)); \
} while (0);
#define expect_single_log_msg_containing(str) \
do { \
assert_log_predicate(mock_saved_log_has_message_containing(str)&& \
mock_saved_log_n_entries() == 1 , \
("expected log to contain 1 message, containing \"%s\"",\
str)); \
} while (0);
#define expect_no_log_msg(str) \
assert_log_predicate(!mock_saved_log_has_message(str), \
("expected log to not contain \"%s\"",str));
#define expect_no_log_msg_containing(str) \
assert_log_predicate(!mock_saved_log_has_message_containing(str), \
("expected log to not contain \"%s\"", str));
#define expect_log_severity(severity) \
assert_log_predicate(mock_saved_log_has_severity(severity), \
("expected log to contain severity " # severity));
#define expect_no_log_severity(severity) \
assert_log_predicate(!mock_saved_log_has_severity(severity), \
("expected log to not contain severity " # severity));
#define expect_log_entry() \
assert_log_predicate(mock_saved_log_has_entry(), \
("expected log to contain entries"));
#define expect_no_log_entry() \
assert_log_predicate(!mock_saved_log_has_entry(), \
("expected log to not contain entries"));
#endif /* !defined(TOR_LOG_TEST_HELPERS_H) */
| zcoinofficial/zcoin | src/tor/src/test/log_test_helpers.h | C | mit | 5,131 |
/*
* The Plaid API
*
* The Plaid REST API. Please see https://plaid.com/docs/api for more details.
*
* API version: 2020-09-14_1.78.0
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package plaid
import (
"encoding/json"
)
// WalletTransactionExecuteResponse WalletTransactionExecuteResponse defines the response schema for `/wallet/transaction/execute`
type WalletTransactionExecuteResponse struct {
// A unique ID identifying the transaction
TransactionId string `json:"transaction_id"`
Status WalletTransactionStatus `json:"status"`
// A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive.
RequestId string `json:"request_id"`
AdditionalProperties map[string]interface{}
}
type _WalletTransactionExecuteResponse WalletTransactionExecuteResponse
// NewWalletTransactionExecuteResponse instantiates a new WalletTransactionExecuteResponse object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewWalletTransactionExecuteResponse(transactionId string, status WalletTransactionStatus, requestId string) *WalletTransactionExecuteResponse {
this := WalletTransactionExecuteResponse{}
this.TransactionId = transactionId
this.Status = status
this.RequestId = requestId
return &this
}
// NewWalletTransactionExecuteResponseWithDefaults instantiates a new WalletTransactionExecuteResponse object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewWalletTransactionExecuteResponseWithDefaults() *WalletTransactionExecuteResponse {
this := WalletTransactionExecuteResponse{}
return &this
}
// GetTransactionId returns the TransactionId field value
func (o *WalletTransactionExecuteResponse) GetTransactionId() string {
if o == nil {
var ret string
return ret
}
return o.TransactionId
}
// GetTransactionIdOk returns a tuple with the TransactionId field value
// and a boolean to check if the value has been set.
func (o *WalletTransactionExecuteResponse) GetTransactionIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.TransactionId, true
}
// SetTransactionId sets field value
func (o *WalletTransactionExecuteResponse) SetTransactionId(v string) {
o.TransactionId = v
}
// GetStatus returns the Status field value
func (o *WalletTransactionExecuteResponse) GetStatus() WalletTransactionStatus {
if o == nil {
var ret WalletTransactionStatus
return ret
}
return o.Status
}
// GetStatusOk returns a tuple with the Status field value
// and a boolean to check if the value has been set.
func (o *WalletTransactionExecuteResponse) GetStatusOk() (*WalletTransactionStatus, bool) {
if o == nil {
return nil, false
}
return &o.Status, true
}
// SetStatus sets field value
func (o *WalletTransactionExecuteResponse) SetStatus(v WalletTransactionStatus) {
o.Status = v
}
// GetRequestId returns the RequestId field value
func (o *WalletTransactionExecuteResponse) GetRequestId() string {
if o == nil {
var ret string
return ret
}
return o.RequestId
}
// GetRequestIdOk returns a tuple with the RequestId field value
// and a boolean to check if the value has been set.
func (o *WalletTransactionExecuteResponse) GetRequestIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.RequestId, true
}
// SetRequestId sets field value
func (o *WalletTransactionExecuteResponse) SetRequestId(v string) {
o.RequestId = v
}
func (o WalletTransactionExecuteResponse) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["transaction_id"] = o.TransactionId
}
if true {
toSerialize["status"] = o.Status
}
if true {
toSerialize["request_id"] = o.RequestId
}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
return json.Marshal(toSerialize)
}
func (o *WalletTransactionExecuteResponse) UnmarshalJSON(bytes []byte) (err error) {
varWalletTransactionExecuteResponse := _WalletTransactionExecuteResponse{}
if err = json.Unmarshal(bytes, &varWalletTransactionExecuteResponse); err == nil {
*o = WalletTransactionExecuteResponse(varWalletTransactionExecuteResponse)
}
additionalProperties := make(map[string]interface{})
if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
delete(additionalProperties, "transaction_id")
delete(additionalProperties, "status")
delete(additionalProperties, "request_id")
o.AdditionalProperties = additionalProperties
}
return err
}
type NullableWalletTransactionExecuteResponse struct {
value *WalletTransactionExecuteResponse
isSet bool
}
func (v NullableWalletTransactionExecuteResponse) Get() *WalletTransactionExecuteResponse {
return v.value
}
func (v *NullableWalletTransactionExecuteResponse) Set(val *WalletTransactionExecuteResponse) {
v.value = val
v.isSet = true
}
func (v NullableWalletTransactionExecuteResponse) IsSet() bool {
return v.isSet
}
func (v *NullableWalletTransactionExecuteResponse) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableWalletTransactionExecuteResponse(val *WalletTransactionExecuteResponse) *NullableWalletTransactionExecuteResponse {
return &NullableWalletTransactionExecuteResponse{value: val, isSet: true}
}
func (v NullableWalletTransactionExecuteResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableWalletTransactionExecuteResponse) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
| plaid/plaid-go | plaid/model_wallet_transaction_execute_response.go | GO | mit | 5,790 |
chrome.app.runtime.onLaunched.addListener(function(){
chrome.app.window.create('index.html', {
bounds: {
width: Math.round(window.screen.availWidth - 100),
height: Math.round(window.screen.availHeight - 100)
}
});
}); | pioul/Minimalist-Markdown-Editor-for-Chrome | src/js/background.js | JavaScript | mit | 230 |
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require "yaml"
shared_examples "a bullet" do
let(:capacity) { 2 }
subject do
described_class.new(:machines => machines, :guns => capacity)
end
describe :fire do
it "spawns correct number of threads" do
bullets = ["first", "second"]
subject.specs = bullets
Parallel.expects(:map).with(bullets, :in_threads => capacity)
subject.fire
end
it "executes loaded specs" do
bullets = ["first", "second"]
subject.specs = bullets
Bullet::BulletClient.any_instance.stubs(:execute).returns("hello")
subject.fire.should == ["hello"] * bullets.length
end
it "unloads after fire" do
bullets = ["first", "second"]
subject.specs = bullets
Bullet::BulletClient.any_instance.stubs(:execute).returns(true)
subject.fire
subject.specs.should have(0).bullets
end
end
end
describe Bullet::BulletClient do
subject { Bullet::BulletClient.new() }
describe :unload do
it "drops all collected specs and plan_list" do
subject.plan_list = {"hello" => 1}
subject.specs = ["test"]
subject.unload
subject.specs.should have(0).spec
end
end
describe :load do
it "collect plans" do
subject.load("dummy_bullet.yml")
subject.plan_list.should eq({"github" => {
"user" => {"register" => 10},
"admin" => {"create_user" => 20}
}})
end
end
describe :aim do
it "choose target as the plan" do
subject.aim("plan")
subject.plan.should == "plan"
end
end
describe :prepare do
it "calculates path to specs" do
subject.plan_list = {"normal" => {"user" => {"signin" => 1, "register" => 2}}}
subject.plan = "normal"
expected = ["user_signin", "user_register", "user_register"]
subject.prepare
(subject.specs.flatten - expected).should be_empty
end
it "distribute specs to machines" do
subject.plan_list = {"normal" => {"user" => {"signin" => 1, "register" => 2}}}
subject.plan = "normal"
subject.machines = 2
subject.prepare
subject.specs.should have(2).sets
end
end
describe :ready? do
it "verifies that specs exists" do
subject.specs = [["hello"]]
subject.ready?.should be_true
end
end
describe :use do
it "accept the path as look up path" do
subject.use("hello")
subject.spec_path.should == "hello"
end
end
context "with threads" do
it_behaves_like "a bullet" do
let(:machines) { 2 }
end
end
context "with processes" do
it_behaves_like "a bullet" do
let(:machines) { 2 }
end
end
end
| dqminh/bullet | spec/bullet_spec.rb | Ruby | mit | 2,702 |
#!/usr/bin/env python
#
# Copyright 2010 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Python client library for the Facebook Platform.
This client library is designed to support the Graph API and the
official Facebook JavaScript SDK, which is the canonical way to
implement Facebook authentication. Read more about the Graph API at
http://developers.facebook.com/docs/api. You can download the Facebook
JavaScript SDK at http://github.com/facebook/connect-js/.
If your application is using Google AppEngine's webapp framework, your
usage of this module might look like this:
user = facebook.get_user_from_cookie(self.request.cookies, key, secret)
if user:
graph = facebook.GraphAPI(user["access_token"])
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
"""
import cgi
import time
import urllib
import urllib2
import httplib
import hashlib
import hmac
import base64
import logging
import socket
# Find a JSON parser
try:
import simplejson as json
except ImportError:
try:
from django.utils import simplejson as json
except ImportError:
import json
_parse_json = json.loads
# Find a query string parser
try:
from urlparse import parse_qs
except ImportError:
from cgi import parse_qs
class GraphAPI(object):
"""A client for the Facebook Graph API.
See http://developers.facebook.com/docs/api for complete
documentation for the API.
The Graph API is made up of the objects in Facebook (e.g., people,
pages, events, photos) and the connections between them (e.g.,
friends, photo tags, and event RSVPs). This client provides access
to those primitive types in a generic way. For example, given an
OAuth access token, this will fetch the profile of the active user
and the list of the user's friends:
graph = facebook.GraphAPI(access_token)
user = graph.get_object("me")
friends = graph.get_connections(user["id"], "friends")
You can see a list of all of the objects and connections supported
by the API at http://developers.facebook.com/docs/reference/api/.
You can obtain an access token via OAuth or by using the Facebook
JavaScript SDK. See
http://developers.facebook.com/docs/authentication/ for details.
If you are using the JavaScript SDK, you can use the
get_user_from_cookie() method below to get the OAuth access token
for the active user from the cookie saved by the SDK.
"""
def __init__(self, access_token=None, timeout=None):
self.access_token = access_token
self.timeout = timeout
def get_object(self, id, **args):
"""Fetchs the given object from the graph."""
return self.request(id, args)
def get_objects(self, ids, **args):
"""Fetchs all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception.
"""
args["ids"] = ",".join(ids)
return self.request("", args)
def get_connections(self, id, connection_name, **args):
"""Fetchs the connections for given object."""
return self.request(id + "/" + connection_name, args)
def put_object(self, parent_object, connection_name, **data):
"""Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user's wall. Likewise, this
will comment on a the first post of the active user's feed:
feed = graph.get_connections("me", "feed")
post = feed["data"][0]
graph.put_object(post["id"], "comments", message="First!")
See http://developers.facebook.com/docs/api#publishing for all
of the supported writeable objects.
Certain write operations require extended permissions. For
example, publishing to a user's feed requires the
"publish_actions" permission. See
http://developers.facebook.com/docs/publishing/ for details
about publishing permissions.
"""
assert self.access_token, "Write operations require an access token"
return self.request(parent_object + "/" + connection_name,
post_args=data)
def put_wall_post(self, message, attachment={}, profile_id="me"):
"""Writes a wall post to the given profile's wall.
We default to writing to the authenticated user's wall if no
profile_id is specified.
attachment adds a structured attachment to the status message
being posted to the Wall. It should be a dictionary of the form:
{"name": "Link name"
"link": "http://www.example.com/",
"caption": "{*actor*} posted a new review",
"description": "This is a longer description of the attachment",
"picture": "http://www.example.com/thumbnail.jpg"}
"""
return self.put_object(profile_id, "feed", message=message,
**attachment)
def put_comment(self, object_id, message):
"""Writes the given comment on the given post."""
return self.put_object(object_id, "comments", message=message)
def put_like(self, object_id):
"""Likes the given post."""
return self.put_object(object_id, "likes")
def delete_object(self, id):
"""Deletes the object with the given ID from the graph."""
self.request(id, post_args={"method": "delete"})
def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
conn = httplib.HTTPSConnection('graph.facebook.com')
url = '/%s_%s?%s' % (
request_id,
user_id,
urllib.urlencode({'access_token': self.access_token}),
)
conn.request('DELETE', url)
response = conn.getresponse()
data = response.read()
response = _parse_json(data)
# Raise an error if we got one, but don't not if Facebook just
# gave us a Bool value
if (response and isinstance(response, dict) and response.get("error")):
raise GraphAPIError(response)
conn.close()
def put_photo(self, image, message=None, album_id=None, **kwargs):
"""Uploads an image using multipart/form-data.
image=File like object for the image
message=Caption for your image
album_id=None posts to /me/photos which uses or creates and uses
an album for your application.
"""
object_id = album_id or "me"
#it would have been nice to reuse self.request;
#but multipart is messy in urllib
post_args = {
'access_token': self.access_token,
'source': image,
'message': message,
}
post_args.update(kwargs)
content_type, body = self._encode_multipart_form(post_args)
req = urllib2.Request(("https://graph.facebook.com/%s/photos" %
object_id),
data=body)
req.add_header('Content-Type', content_type)
try:
data = urllib2.urlopen(req).read()
#For Python 3 use this:
#except urllib2.HTTPError as e:
except urllib2.HTTPError, e:
data = e.read() # Facebook sends OAuth errors as 400, and urllib2
# throws an exception, we want a GraphAPIError
try:
response = _parse_json(data)
# Raise an error if we got one, but don't not if Facebook just
# gave us a Bool value
if (response and isinstance(response, dict) and
response.get("error")):
raise GraphAPIError(response)
except ValueError:
response = data
return response
# based on: http://code.activestate.com/recipes/146306/
def _encode_multipart_form(self, fields):
"""Encode files as 'multipart/form-data'.
Fields are a dict of form name-> value. For files, value should
be a file object. Other file-like objects might work and a fake
name will be chosen.
Returns (content_type, body) ready for httplib.HTTP instance.
"""
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields.items():
logging.debug("Encoding %s, (%s)%s" % (key, type(value), value))
if not value:
continue
L.append('--' + BOUNDARY)
if hasattr(value, 'read') and callable(value.read):
filename = getattr(value, 'name', '%s.jpg' % key)
L.append(('Content-Disposition: form-data;'
'name="%s";'
'filename="%s"') % (key, filename))
L.append('Content-Type: image/jpeg')
value = value.read()
logging.debug(type(value))
else:
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
if isinstance(value, unicode):
logging.debug("Convert to ascii")
value = value.encode('ascii')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
def request(self, path, args=None, post_args=None):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.
"""
args = args or {}
if self.access_token:
if post_args is not None:
post_args["access_token"] = self.access_token
else:
args["access_token"] = self.access_token
post_data = None if post_args is None else urllib.urlencode(post_args)
try:
file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" +
urllib.urlencode(args),
post_data, timeout=self.timeout)
except urllib2.HTTPError, e:
response = _parse_json(e.read())
raise GraphAPIError(response)
except TypeError:
# Timeout support for Python <2.6
if self.timeout:
socket.setdefaulttimeout(self.timeout)
file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" +
urllib.urlencode(args), post_data)
try:
fileInfo = file.info()
if fileInfo.maintype == 'text':
response = _parse_json(file.read())
elif fileInfo.maintype == 'image':
mimetype = fileInfo['content-type']
response = {
"data": file.read(),
"mime-type": mimetype,
"url": file.url,
}
else:
raise GraphAPIError('Maintype was not text or image')
finally:
file.close()
if response and isinstance(response, dict) and response.get("error"):
raise GraphAPIError(response["error"]["type"],
response["error"]["message"])
return response
def fql(self, query, args=None, post_args=None):
"""FQL query.
Example query: "SELECT affiliations FROM user WHERE uid = me()"
"""
args = args or {}
if self.access_token:
if post_args is not None:
post_args["access_token"] = self.access_token
else:
args["access_token"] = self.access_token
post_data = None if post_args is None else urllib.urlencode(post_args)
"""Check if query is a dict and
use the multiquery method
else use single query
"""
if not isinstance(query, basestring):
args["queries"] = query
fql_method = 'fql.multiquery'
else:
args["query"] = query
fql_method = 'fql.query'
args["format"] = "json"
try:
file = urllib2.urlopen("https://api.facebook.com/method/" +
fql_method + "?" + urllib.urlencode(args),
post_data, timeout=self.timeout)
except TypeError:
# Timeout support for Python <2.6
if self.timeout:
socket.setdefaulttimeout(self.timeout)
file = urllib2.urlopen("https://api.facebook.com/method/" +
fql_method + "?" + urllib.urlencode(args),
post_data)
try:
content = file.read()
response = _parse_json(content)
#Return a list if success, return a dictionary if failed
if type(response) is dict and "error_code" in response:
raise GraphAPIError(response)
except Exception, e:
raise e
finally:
file.close()
return response
def extend_access_token(self, app_id, app_secret):
"""
Extends the expiration time of a valid OAuth access token. See
<https://developers.facebook.com/roadmap/offline-access-removal/
#extend_token>
"""
args = {
"client_id": app_id,
"client_secret": app_secret,
"grant_type": "fb_exchange_token",
"fb_exchange_token": self.access_token,
}
response = urllib.urlopen("https://graph.facebook.com/oauth/"
"access_token?" +
urllib.urlencode(args)).read()
query_str = parse_qs(response)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
return result
else:
response = json.loads(response)
raise GraphAPIError(response)
class GraphAPIError(Exception):
def __init__(self, result):
#Exception.__init__(self, message)
#self.type = type
self.result = result
try:
self.type = result["error_code"]
except:
self.type = ""
# OAuth 2.0 Draft 10
try:
self.message = result["error_description"]
except:
# OAuth 2.0 Draft 00
try:
self.message = result["error"]["message"]
except:
# REST server style
try:
self.message = result["error_msg"]
except:
self.message = result
Exception.__init__(self, self.message)
def get_user_from_cookie(cookies, app_id, app_secret):
"""Parses the cookie set by the official Facebook JavaScript SDK.
cookies should be a dictionary-like object mapping cookie names to
cookie values.
If the user is logged in via Facebook, we return a dictionary with
the keys "uid" and "access_token". The former is the user's
Facebook ID, and the latter can be used to make authenticated
requests to the Graph API. If the user is not logged in, we
return None.
Download the official Facebook JavaScript SDK at
http://github.com/facebook/connect-js/. Read more about Facebook
authentication at
http://developers.facebook.com/docs/authentication/.
"""
cookie = cookies.get("fbsr_" + app_id, "")
if not cookie:
return None
parsed_request = parse_signed_request(cookie, app_secret)
if not parsed_request:
return None
try:
result = get_access_token_from_code(parsed_request["code"], "",
app_id, app_secret)
except GraphAPIError:
return None
result["uid"] = parsed_request["user_id"]
return result
def parse_signed_request(signed_request, app_secret):
""" Return dictionary with signed request data.
We return a dictionary containing the information in the
signed_request. This includes a user_id if the user has authorised
your application, as well as any information requested.
If the signed_request is malformed or corrupted, False is returned.
"""
try:
encoded_sig, payload = map(str, signed_request.split('.', 1))
sig = base64.urlsafe_b64decode(encoded_sig + "=" *
((4 - len(encoded_sig) % 4) % 4))
data = base64.urlsafe_b64decode(payload + "=" *
((4 - len(payload) % 4) % 4))
except IndexError:
# Signed request was malformed.
return False
except TypeError:
# Signed request had a corrupted payload.
return False
data = _parse_json(data)
if data.get('algorithm', '').upper() != 'HMAC-SHA256':
return False
# HMAC can only handle ascii (byte) strings
# http://bugs.python.org/issue5285
app_secret = app_secret.encode('ascii')
payload = payload.encode('ascii')
expected_sig = hmac.new(app_secret,
msg=payload,
digestmod=hashlib.sha256).digest()
if sig != expected_sig:
return False
return data
def auth_url(app_id, canvas_url, perms=None, **kwargs):
url = "https://www.facebook.com/dialog/oauth?"
kvps = {'client_id': app_id, 'redirect_uri': canvas_url}
if perms:
kvps['scope'] = ",".join(perms)
kvps.update(kwargs)
return url + urllib.urlencode(kvps)
def get_access_token_from_code(code, redirect_uri, app_id, app_secret):
"""Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable).
"""
args = {
"code": code,
"redirect_uri": redirect_uri,
"client_id": app_id,
"client_secret": app_secret,
}
# We would use GraphAPI.request() here, except for that the fact
# that the response is a key-value pair, and not JSON.
response = urllib.urlopen("https://graph.facebook.com/oauth/access_token" +
"?" + urllib.urlencode(args)).read()
query_str = parse_qs(response)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
return result
else:
response = json.loads(response)
raise GraphAPIError(response)
def get_app_access_token(app_id, app_secret):
"""Get the access_token for the app.
This token can be used for insights and creating test users.
app_id = retrieved from the developer page
app_secret = retrieved from the developer page
Returns the application access_token.
"""
# Get an app access token
args = {'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': app_secret}
file = urllib2.urlopen("https://graph.facebook.com/oauth/access_token?" +
urllib.urlencode(args))
try:
result = file.read().split("=")[1]
finally:
file.close()
return result
| Agnishom/ascii-art-007 | facebook.py | Python | mit | 20,087 |
FactoryGirl.define do
factory :transaction do |t|
t.description "Test transaction"
t.association :account_from, :factory => :foo_account
t.association :account_to, :factory => :foo_account
t.amount 10.00
end
factory :invoice_payment, :parent => :transaction do
auxilliary_model :factory => :invoice
end
end
| logicleague/double_booked | spec/factories/transaction_factory.rb | Ruby | mit | 340 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>TableTools example - Button collections</title>
<link rel="stylesheet" type="text/css" href="../../../media/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="../css/dataTables.tableTools.css">
<link rel="stylesheet" type="text/css" href="../../../examples/resources/syntax/shCore.css">
<link rel="stylesheet" type="text/css" href="../../../examples/resources/demo.css">
<style type="text/css" class="init">
</style>
<script type="text/javascript" language="javascript" src="../../../media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="../../../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" src="../js/dataTables.tableTools.js"></script>
<script type="text/javascript" language="javascript" src="../../../examples/resources/syntax/shCore.js"></script>
<script type="text/javascript" language="javascript" src="../../../examples/resources/demo.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
$('#example').DataTable( {
"dom": 'T<"clear">lfrtip',
"tableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": "Save",
"aButtons": [ "csv", "xls", "pdf" ]
}
]
}
} );
} );
</script>
</head>
<body class="dt-example">
<div class="container">
<section>
<h1>TableTools example <span>Button collections</span></h1>
<div class="info">
<p>TableTools provides the ability to group buttons into a hidden drop down list, which is activated by clicking on a top-level button. This is achieved by
extending the 'collection' predefined button type and setting it's <code>aButtons</code> parameter with the same options as the top level buttons (note that you
cannot currently use a collection within a collection).</p>
<p>The example below shows the file save buttons grouped into a collection, while the copy and print buttons are left on the top level.</p>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
</tr>
<tr>
<td>Colleen Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
</tr>
<tr>
<td>Sonya Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
</tr>
<tr>
<td>Jena Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
</tr>
<tr>
<td>Quinn Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
</tr>
<tr>
<td>Charde Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
</tr>
<tr>
<td>Haley Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
</tr>
<tr>
<td>Tatyana Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
</tr>
<tr>
<td>Michael Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
</tr>
<tr>
<td>Paul Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
</tr>
<tr>
<td>Gloria Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
</tr>
<tr>
<td>Bradley Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
</tr>
<tr>
<td>Dai Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
</tr>
<tr>
<td>Jenette Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
</tr>
<tr>
<td>Yuri Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
</tr>
<tr>
<td>Caesar Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
</tr>
<tr>
<td>Doris Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
</tr>
<tr>
<td>Angelica Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
</tr>
<tr>
<td>Gavin Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
</tr>
<tr>
<td>Jennifer Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
</tr>
<tr>
<td>Brenden Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
</tr>
<tr>
<td>Fiona Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
</tr>
<tr>
<td>Shou Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
</tr>
<tr>
<td>Michelle House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
</tr>
<tr>
<td>Suki Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
</tr>
<tr>
<td>Prescott Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
</tr>
<tr>
<td>Gavin Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
</tr>
<tr>
<td>Martena Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
</tr>
<tr>
<td>Unity Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
</tr>
<tr>
<td>Howard Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
</tr>
<tr>
<td>Hope Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
</tr>
<tr>
<td>Vivian Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
</tr>
<tr>
<td>Timothy Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
</tr>
<tr>
<td>Jackson Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
</tr>
<tr>
<td>Olivia Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
</tr>
<tr>
<td>Bruno Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
</tr>
<tr>
<td>Sakura Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
</tr>
<tr>
<td>Thor Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
</tr>
<tr>
<td>Finn Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
</tr>
<tr>
<td>Serge Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
</tr>
<tr>
<td>Zenaida Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
</tr>
<tr>
<td>Zorita Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
</tr>
<tr>
<td>Jennifer Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
</tr>
<tr>
<td>Cara Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
</tr>
<tr>
<td>Hermione Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
</tr>
<tr>
<td>Lael Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
</tr>
<tr>
<td>Jonas Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
</tr>
<tr>
<td>Shad Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
</tr>
<tr>
<td>Michael Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
</tr>
<tr>
<td>Donna Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
</tr>
</tbody>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<div class="js">
<p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline language-js">$(document).ready(function() {
$('#example').DataTable( {
"dom": 'T<"clear">lfrtip',
"tableTools": {
"aButtons": [
"copy",
"print",
{
"sExtends": "collection",
"sButtonText": "Save",
"aButtons": [ "csv", "xls", "pdf" ]
}
]
}
} );
} );</code>
<p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p>
<ul>
<li><a href="../../../media/js/jquery.js">../../../media/js/jquery.js</a></li>
<li><a href="../../../media/js/jquery.dataTables.js">../../../media/js/jquery.dataTables.js</a></li>
<li><a href="../js/dataTables.tableTools.js">../js/dataTables.tableTools.js</a></li>
</ul>
</div>
<div class="table">
<p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p>
</div>
<div class="css">
<div>
<p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The
additional CSS used is shown below:</p><code class="multiline language-css"></code>
</div>
<p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p>
<ul>
<li><a href="../../../media/css/jquery.dataTables.css">../../../media/css/jquery.dataTables.css</a></li>
<li><a href="../css/dataTables.tableTools.css">../css/dataTables.tableTools.css</a></li>
</ul>
</div>
<div class="ajax">
<p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is
loaded.</p>
</div>
<div class="php">
<p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side
processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables
documentation</a>.</p>
</div>
</div>
</section>
</div>
<section>
<div class="footer">
<div class="gradient"></div>
<div class="liner">
<h2>Other examples</h2>
<div class="toc">
<div class="toc-group">
<h3><a href="./index.php">Examples</a></h3>
<ul class="toc active">
<li><a href="./simple.html">Basic initialisation</a></li>
<li><a href="./swf_path.html">Setting the SWF path</a></li>
<li><a href="./new_init.html">Initialisation with `new`</a></li>
<li><a href="./defaults.html">Defaults</a></li>
<li><a href="./select_single.html">Row selection - single row select</a></li>
<li><a href="./select_multi.html">Row selection - multi-row select</a></li>
<li><a href="./select_os.html">Row selection - operating system style</a></li>
<li><a href="./select_column.html">Row selection - row selector on specific cells</a></li>
<li><a href="./multiple_tables.html">Multiple tables</a></li>
<li><a href="./multi_instance.html">Multiple toolbars</a></li>
<li class="active"><a href="./collection.html">Button collections</a></li>
<li><a href="./plug-in.html">Plug-in button types</a></li>
<li><a href="./button_text.html">Custom button text</a></li>
<li><a href="./alter_buttons.html">Button arrangement</a></li>
<li><a href="./ajax.html">Ajax loaded data</a></li>
<li><a href="./pdf_message.html">PDF message</a></li>
<li><a href="./bootstrap.html">Bootstrap styling</a></li>
<li><a href="./jqueryui.html">jQuery UI styling</a></li>
</ul>
</div>
</div>
<div class="epilogue">
<p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and <a href="http://www.datatables.net/plug-ins">plug-ins</a>
which extend the capabilities of DataTables.</p>
<p class="copyright">DataTables designed and created by <a href="http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2015<br>
DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p>
</div>
</div>
</div>
</section>
</body>
</html> | SLM2A/site_adm | site/plugins/datatables/extensions/TableTools/examples/collection.html | HTML | mit | 17,621 |
//
// AppDelegate.h
// EXTabBarController
//
// Created by apple on 15/5/23.
// Copyright (c) 2015年 DeltaX. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| Draveness/EXTabBarController | EXTabBarController/AppDelegate.h | C | mit | 282 |
"use strict";
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
var task = require("../tasks/tar.gz"),
fs = require("fs");
exports["targz"] = {
setUp: function(done) {
// setup here
done();
},
"targz sqlite3": function(test) {
test.expect(1);
var actual;
actual = fs.statSync("tmp/node_sqlite3.node");
test.equal(actual.size, 831488);
test.done();
}
}; | bendi/grunt-tar.gz | test/tar.gz_test.js | JavaScript | mit | 1,003 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Comp625Component } from './comp-625.component';
describe('Comp625Component', () => {
let component: Comp625Component;
let fixture: ComponentFixture<Comp625Component>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ Comp625Component ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Comp625Component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| angular/angular-cli-stress-test | src/app/components/comp-625/comp-625.component.spec.ts | TypeScript | mit | 840 |
require 'moosex/types'
require 'moosex/attribute/modifiers'
module MooseX
class Attribute
include MooseX::Types
attr_reader :attr_symbol, :methods, :attribute_map
def is ; @attribute_map[:is] ; end
def writter ; @attribute_map[:writter] ; end
def reader ; @attribute_map[:reader] ; end
def override ; @attribute_map[:override] ; end
def doc ; @attribute_map[:doc] ; end
def default ; @attribute_map[:default] ; end
@@LIST_OF_PARAMETERS = [
:is, #MooseX::AttributeModifiers::Is ],
:isa, #MooseX::AttributeModifiers::Isa ],
:default, #MooseX::AttributeModifiers::Default ],
:required, #MooseX::AttributeModifiers::Required ],
:predicate, #MooseX::AttributeModifiers::Predicate],
:clearer, #MooseX::AttributeModifiers::Clearer ],
:traits, #MooseX::AttributeModifiers::Traits ],
:handles, #MooseX::AttributeModifiers::Handles ],
:lazy, #MooseX::AttributeModifiers::Lazy ],
:reader, #MooseX::AttributeModifiers::Reader ],
:writter, #MooseX::AttributeModifiers::Writter ],
:builder, #MooseX::AttributeModifiers::Builder ],
:init_arg, #MooseX::AttributeModifiers::Init_arg ],
:trigger, #MooseX::AttributeModifiers::Trigger ],
:coerce, #MooseX::AttributeModifiers::Coerce ],
:weak, #MooseX::AttributeModifiers::Weak ],
:doc, #MooseX::AttributeModifiers::Doc ],
:override, #MooseX::AttributeModifiers::Override ],
]
def initialize(attr_symbol, options ,klass)
@attr_symbol = attr_symbol
@attribute_map = {}
init_internal_modifiers(options.clone, klass.__moosex__meta.plugins, klass)
end
def init_internal_modifiers(options, plugins, klass)
list = @@LIST_OF_PARAMETERS.map do |parameter|
MooseX::AttributeModifiers::const_get(parameter.capitalize).new(self)
end
list.each do |plugin|
plugin.prepare(options)
end
plugins.sort.uniq.each do |plugin_klass|
begin
plugin_klass.new(self).prepare(options)
rescue => e
raise "Unexpected Error in #{klass} #{plugin_klass} #{@attr_symbol}: #{e}"
end
end
list.each do |plugin|
plugin.process(options)
end
generate_all_methods
plugins.sort.uniq.each do |plugin_klass|
begin
plugin_klass.new(self).process(options)
rescue NameError => e
next
rescue => e
raise "Unexpected Error in #{klass} #{plugin_klass} #{@attr_symbol}: #{e}"
end
end
MooseX.warn "Unused attributes #{options} for attribute #{@attr_symbol} @ #{klass} #{klass.class}",caller() if ! options.empty?
end
def generate_all_methods
@methods = {}
if @attribute_map[:reader]
@methods[@attribute_map[:reader]] = generate_reader
end
if @attribute_map[:writter]
@methods[@attribute_map[:writter]] = generate_writter
end
inst_variable_name = "@#{@attr_symbol}".to_sym
if @attribute_map[:predicate]
@methods[@attribute_map[:predicate]] = ->(this) do
this.instance_variable_defined? inst_variable_name
end
end
if @attribute_map[:clearer]
@methods[@attribute_map[:clearer]] = ->(this) do
if this.instance_variable_defined? inst_variable_name
this.remove_instance_variable inst_variable_name
end
end
end
generate_handles @attr_symbol
end
def generate_handles(attr_symbol)
delegator = ->(this) { this.__send__(attr_symbol) }
@attribute_map[:handles].each_pair do | method, target_method |
if target_method.is_a? Array
original_method, currying = target_method
@methods[method] = generate_handles_with_currying(delegator, original_method, currying)
else
@methods[method] = Proc.new do |this, *args, &proc|
delegator.call(this).__send__(target_method, *args, &proc)
end
end
end
end
def generate_handles_with_currying(delegator, original_method, currying)
Proc.new do |this, *args, &proc|
a1 = [ currying ]
if currying.is_a?Proc
a1 = currying[]
elsif currying.is_a? Array
a1 = currying.map{|c| (c.is_a?(Proc)) ? c[] : c }
end
delegator.call(this).__send__(original_method, *a1, *args, &proc)
end
end
def init(object, args)
value = nil
value_from_default = false
if args.has_key? @attribute_map[:init_arg]
value = args.delete(@attribute_map[:init_arg])
elsif @attribute_map[:default]
value = @attribute_map[:default].call
value_from_default = true
elsif @attribute_map[:required]
raise InvalidAttributeError, "attr \"#{@attr_symbol}\" is required"
else
return
end
value = @attribute_map[:coerce].call(value)
begin
@attribute_map[:isa].call( value )
rescue MooseX::Types::TypeCheckError => e
raise MooseX::Types::TypeCheckError, "isa check for field #{attr_symbol}: #{e}"
end
unless value_from_default
@attribute_map[:trigger].call(object, value)
end
value = @attribute_map[:traits].call(value)
inst_variable_name = "@#{@attr_symbol}".to_sym
object.instance_variable_set inst_variable_name, value
end
def generate_reader
inst_variable_name = "@#{@attr_symbol}".to_sym
builder = @attribute_map[:builder]
before_get = ->(object) { }
if @attribute_map[:lazy]
type_check = protect_isa(@attribute_map[:isa], "isa check for #{inst_variable_name} from builder")
coerce = @attribute_map[:coerce]
trigger = @attribute_map[:trigger]
traits = @attribute_map[:traits]
before_get = ->(object) do
return if object.instance_variable_defined? inst_variable_name
value = builder.call(object)
value = coerce.call(value)
type_check.call( value )
trigger.call(object, value)
value = traits.call(value)
object.instance_variable_set(inst_variable_name, value)
end
end
->(this) do
before_get.call(this)
this.instance_variable_get inst_variable_name
end
end
def protect_isa(type_check, message)
->(value) do
begin
type_check.call( value )
rescue MooseX::Types::TypeCheckError => e
raise MooseX::Types::TypeCheckError, "#{message}: #{e}"
end
end
end
def generate_writter
writter_name = @attribute_map[:writter]
inst_variable_name = "@#{@attr_symbol}".to_sym
coerce = @attribute_map[:coerce]
type_check = protect_isa(@attribute_map[:isa], "isa check for #{writter_name}")
trigger = @attribute_map[:trigger]
traits = @attribute_map[:traits]
->(this, value) do
value = coerce.call(value)
type_check.call( value )
trigger.call(this,value)
value = traits.call(value)
this.instance_variable_set inst_variable_name, value
end
end
end
end | peczenyj/MooseX | lib/moosex/attribute.rb | Ruby | mit | 7,509 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login Page - Photon Admin Panel Theme</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<link rel="shortcut icon" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/favicon.ico"/>
<link rel="apple-touch-icon" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/iosicon.png"/>
<link rel="stylesheet" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/css/css_compiled/photon-min.css?v1.1" media="all"/>
<link rel="stylesheet" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/css/css_compiled/photon-min-part2.css?v1.1" media="all"/>
<link rel="stylesheet" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/css/css_compiled/photon-responsive-min.css?v1.1" media="all"/>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="css/css_compiled/ie-only-min.css?v1.1" />
<![endif]-->
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="css/css_compiled/ie8-only-min.css?v1.1" />
<script type="text/javascript" src="js/plugins/excanvas.js"></script>
<script type="text/javascript" src="js/plugins/html5shiv.js"></script>
<script type="text/javascript" src="js/plugins/respond.min.js"></script>
<script type="text/javascript" src="js/plugins/fixFontIcons.js"></script>
<![endif]-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/bootstrap/bootstrap.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/modernizr.custom.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.pnotify.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/less-1.3.1.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/xbreadcrumbs.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.maskedinput-1.3.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.autotab-1.1b.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/charCount.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.textareaCounter.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/elrte.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/elrte.en.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/select2.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery-picklist.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/additional-methods.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.form.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.metadata.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.mockjax.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.uniform.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.tagsinput.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.rating.pack.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/farbtastic.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.timeentry.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.jstree.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.mousewheel.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.mCustomScrollbar.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.flot.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.flot.stack.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.flot.pie.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.flot.resize.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/raphael.2.1.0.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/justgage.1.0.1.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.qrcode.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.clock.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.countdown.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.jqtweet.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/jquery.cookie.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/bootstrap-fileupload.min.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/prettify/prettify.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/bootstrapSwitch.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/plugins/mfupload.js"></script>
<script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/js/common.js"></script>
</head>
<body class="body-login">
<div class="nav-fixed-topright" style="visibility: hidden">
<ul class="nav nav-user-menu">
<li class="user-sub-menu-container">
<a href="javascript:;">
<i class="user-icon"></i><span class="nav-user-selection">Theme Options</span><i class="icon-menu-arrow"></i>
</a>
<ul class="nav user-sub-menu">
<li class="light">
<a href="javascript:;">
<i class='icon-photon stop'></i>Light Version
</a>
</li>
<li class="dark">
<a href="javascript:;">
<i class='icon-photon stop'></i>Dark Version
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-photon mail"></i>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-photon comment_alt2_stroke"></i>
<div class="notification-count">12</div>
</a>
</li>
</ul>
</div>
<script>
$(function(){
setTimeout(function(){
$('.nav-fixed-topright').removeAttr('style');
}, 300);
$(window).scroll(function(){
if($('.breadcrumb-container').length){
var scrollState = $(window).scrollTop();
if (scrollState > 0) $('.nav-fixed-topright').addClass('nav-released');
else $('.nav-fixed-topright').removeClass('nav-released')
}
});
$('.user-sub-menu-container').on('click', function(){
$(this).toggleClass('active-user-menu');
});
$('.user-sub-menu .light').on('click', function(){
if ($('body').is('.light-version')) return;
$('body').addClass('light-version');
setTimeout(function() {
$.cookie('themeColor', 'light', {
expires: 7,
path: '/'
});
}, 500);
});
$('.user-sub-menu .dark').on('click', function(){
if ($('body').is('.light-version')) {
$('body').removeClass('light-version');
$.cookie('themeColor', 'dark', {
expires: 7,
path: '/'
});
}
});
});
</script>
<div class="container-login">
<div class="form-centering-wrapper">
<div class="form-window-login">
<div class="form-window-login-logo">
<div class="login-logo">
<img src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/images/photon/[email protected]" alt="Photon UI"/>
</div>
<h2 class="login-title">Welcome to Photon UI!</h2>
<div class="login-member">Not a Member? <a href="jquery.flot.resize.js.html#">Sign Up »</a>
<a href="jquery.flot.resize.js.html#" class="btn btn-facebook"><i class="icon-fb"></i>Login with Facebook<i class="icon-fb-arrow"></i></a>
</div>
<div class="login-or">Or</div>
<div class="login-input-area">
<form method="POST" action="dashboard.php">
<span class="help-block">Login With Your Photon Account</span>
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="btn btn-large btn-success btn-login">Login</button>
</form>
<a href="jquery.flot.resize.js.html#" class="forgot-pass">Forgot Your Password?</a>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1936460-27']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
| user-tony/photon-rails | lib/assets/images/photon/plugins/elrte/css/css_compiled/js/bootstrap/css/css_compiled/js/plugins/jquery.flot.resize.js.html | HTML | mit | 14,403 |
/*
* Copyright (c) 2011-2016, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.filter.binary;
import boofcv.struct.ConnectRule;
import boofcv.struct.image.GrayS32;
import boofcv.struct.image.GrayU8;
import georegression.struct.point.Point2D_I32;
import sapphire.app.SapphireObject;
import org.ddogleg.struct.FastQueue;
import java.util.List;
/**
* Used to trace the external and internal contours around objects for {@link LinearContourLabelChang2004}. As it
* is tracing an object it will modify the binary image by labeling. The input binary image is assumed to have
* a 1-pixel border that needs to be compensated for.
*
* @author Peter Abeles
*/
public class ContourTracer implements SapphireObject {
// which connectivity rule is being used. 4 and 8 supported
private ConnectRule rule;
private int ruleN;
// storage for contour points.
private FastQueue<Point2D_I32> storagePoints;
// binary image being traced
private GrayU8 binary;
// label image being marked
private GrayS32 labeled;
// storage for contour
private List<Point2D_I32> contour;
// coordinate of pixel being examined (x,y)
private int x,y;
// label of the object being traced
private int label;
// direction it moved in
private int dir;
// index of the pixel in the image's internal array
private int indexBinary;
private int indexLabel;
// the pixel index offset to each neighbor
private int offsetsBinary[];
private int offsetsLabeled[];
// lookup table for which direction it should search next given the direction it traveled into the current pixel
private int nextDirection[];
/**
* Specifies connectivity rule
*
* @param rule Specifies 4 or 8 as connectivity rule
*/
public ContourTracer( ConnectRule rule ) {
this.rule = rule;
if( ConnectRule.EIGHT == rule ) {
// start the next search +2 away from the square it came from
// the square it came from is the opposite from the previous 'dir'
nextDirection = new int[8];
for( int i = 0; i < 8; i++ )
nextDirection[i] = ((i+4)%8 + 2)%8;
ruleN = 8;
} else if( ConnectRule.FOUR == rule ) {
nextDirection = new int[4];
for( int i = 0; i < 4; i++ )
nextDirection[i] = ((i+2)%4 + 1)%4;
ruleN = 4;
} else {
throw new IllegalArgumentException("Connectivity rule must be 4 or 8 not "+rule);
}
offsetsBinary = new int[ruleN];
offsetsLabeled = new int[ruleN];
}
/**
*
* @param binary Binary image with a border of zeros added to the outside.
* @param labeled Labeled image. Size is the same as the original binary image without border.
* @param storagePoints
*/
public void setInputs(GrayU8 binary , GrayS32 labeled , FastQueue<Point2D_I32> storagePoints ) {
this.binary = binary;
this.labeled = labeled;
this.storagePoints = storagePoints;
if( rule == ConnectRule.EIGHT ) {
setOffsets8(offsetsBinary,binary.stride);
setOffsets8(offsetsLabeled,labeled.stride);
} else {
setOffsets4(offsetsBinary,binary.stride);
setOffsets4(offsetsLabeled,labeled.stride);
}
}
private void setOffsets8( int offsets[] , int stride ) {
int s = stride;
offsets[0] = 1; // x = 1 y = 0
offsets[1] = 1+s; // x = 1 y = 1
offsets[2] = s; // x = 0 y = 1
offsets[3] = -1+s; // x = -1 y = 1
offsets[4] = -1 ; // x = -1 y = 0
offsets[5] = -1-s; // x = -1 y = -1
offsets[6] = -s; // x = 0 y = -1
offsets[7] = 1-s; // x = 1 y = -1
}
private void setOffsets4( int offsets[] , int stride ) {
int s = stride;
offsets[0] = 1; // x = 1 y = 0
offsets[1] = s; // x = 0 y = 1
offsets[2] = -1; // x = -1 y = 0
offsets[3] = -s; // x = 0 y = -1
}
/**
*
* @param label
* @param initialX
* @param initialY
* @param external True for tracing an external contour or false for internal..
* @param contour
*/
public void trace( int label , int initialX , int initialY , boolean external , List<Point2D_I32> contour )
{
int initialDir;
if( rule == ConnectRule.EIGHT )
initialDir = external ? 7 : 3;
else
initialDir = external ? 0 : 2;
this.label = label;
this.contour = contour;
this.dir = initialDir;
x = initialX;
y = initialY;
// index of pixels in the image array
// binary has a 1 pixel border which labeled lacks, hence the -1,-1 for labeled
indexBinary = binary.getIndex(x,y);
indexLabel = labeled.getIndex(x-1,y-1);
add(x,y);
// find the next black pixel. handle case where its an isolated point
if( !searchBlack() ) {
return;
} else {
initialDir = dir;
moveToNext();
dir = nextDirection[dir];
}
while( true ) {
// search in clockwise direction around the current pixel for next black pixel
searchBlack();
if( x == initialX && y == initialY && dir == initialDir ) {
// returned to the initial state again. search is finished
return;
}else {
add(x, y);
moveToNext();
dir = nextDirection[dir];
}
}
}
/**
* Searches in a circle around the current point in a clock-wise direction for the first black pixel.
*/
private boolean searchBlack() {
for( int i = 0; i < offsetsBinary.length; i++ ) {
if( checkBlack(indexBinary + offsetsBinary[dir]))
return true;
dir = (dir+1)%ruleN;
}
return false;
}
/**
* Checks to see if the specified pixel is black (1). If not the pixel is marked so that it
* won't be searched again
*/
private boolean checkBlack( int index ) {
if( binary.data[index] == 1 ) {
return true;
} else {
// mark white pixels as negative numbers to avoid retracing this contour in the future
binary.data[index] = -1;
return false;
}
}
private void moveToNext() {
// move to the next pixel using the precomputed pixel index offsets
indexBinary += offsetsBinary[dir];
indexLabel += offsetsLabeled[dir];
// compute the new pixel coordinate from the binary pixel index
int a = indexBinary - binary.startIndex;
x = a%binary.stride;
y = a/binary.stride;
}
/**
* Adds a point to the contour list
*/
private void add( int x , int y ) {
Point2D_I32 p = storagePoints.grow();
// compensate for the border added to binary image
p.set(x-1, y-1);
contour.add(p);
labeled.data[indexLabel] = label;
}
}
| bladestery/Sapphire | example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/alg/filter/binary/ContourTracer.java | Java | mit | 6,808 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Console.Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Console.Server")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("a7943db8-a75d-467f-aa1e-96134b5739ea")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| IKende/IKendeLib | BeetleDemo/Examples/Console/Console.Server/Console.Server/Properties/AssemblyInfo.cs | C# | mit | 1,324 |
#include<stdio.h>
int main(void)
{
double a,b;
printf("Enter a\&b:\n");
while(scanf("%lf%lf",&a,&b)==2)
{
printf("%.3g - %.3g / %.3g * %.3g = %.3g .\n",a,b,a,b,(double)(a-b)/(a*b));
printf("\n");
printf("Enter a\&b:\n");
}
printf("done!");
return 0;
}
| programingc42/testC | ch6/PE6.8.c | C | mit | 252 |
using Microsoft.SPOT.Hardware;
namespace GrFamily.MainBoard
{
/// <summary>
/// LEDNX
/// </summary>
public class Led
{
/// <summary>LEDªÚ±³ê½s</summary>
protected readonly OutputPort LedPort;
/// <summary>
/// RXgN^
/// </summary>
/// <param name="pin">LEDªÚ±³ê½s</param>
public Led(Cpu.Pin pin)
{
LedPort = new OutputPort(pin, false);
}
/// <summary>
/// LEDð_^Á·é
/// </summary>
/// <param name="on">LEDð_·éêÍ trueAÁ·éêÍ false</param>
public void SetLed(bool on)
{
LedPort.Write(on);
}
}
}
| netmf-lib-grfamily/GrFamilyLibrary | Library/MainBoard/Peach/Led.cs | C# | mit | 733 |
FROM midvalestudent/jupyter-scipy:latest
USER root
ENV HOME /root
ADD requirements.txt /usr/local/share/requirements.txt
RUN pip install --upgrade pip && pip install -r /usr/local/share/requirements.txt
# Download/build/install ffmpeg
ARG FFMPEG_VERSION
ENV FFMPEG_VERSION ${FFMPEG_VERSION:-"3.2"}
RUN DEBIAN_FRONTEND=noninteractive \
&& REPO=http://www.deb-multimedia.org \
&& echo "deb $REPO jessie main non-free\ndeb-src $REPO jessie main non-free" >> /etc/apt/sources.list \
&& apt-get update && apt-get install -y --force-yes deb-multimedia-keyring && apt-get update \
&& apt-get remove ffmpeg \
&& apt-get install -yq --no-install-recommends \
build-essential \
libmp3lame-dev \
libvorbis-dev \
libtheora-dev \
libspeex-dev \
yasm \
pkg-config \
libfaac-dev \
libopenjpeg-dev \
libx264-dev \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /usr/src/build && cd /usr/src/build \
&& wget http://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.gz \
&& tar xzf ffmpeg-$FFMPEG_VERSION.tar.gz && cd ffmpeg-$FFMPEG_VERSION \
&& ./configure \
--prefix=/usr/local \
--enable-gpl \
--enable-postproc \
--enable-swscale \
--enable-avfilter \
--enable-libmp3lame \
--enable-libvorbis \
--enable-libtheora \
--enable-libx264 \
--enable-libspeex \
--enable-shared \
--enable-pthreads \
--enable-libopenjpeg \
--enable-nonfree \
&& make -j$(nproc) install && ldconfig \
&& cd /usr/src/build && rm -rf ffmpeg-$FFMPEG_VERSION* \
&& apt-get purge -y cmake && apt-get autoremove -y --purge
# Download/build/install components for opencv
ARG OPENCV_VERSION
ENV OPENCV_VERSION ${OPENCV_VERSION:-"3.2.0"}
RUN DEBIAN_FRONTEND=noninteractive \
&& REPO=http://cdn-fastly.deb.debian.org \
&& echo "deb $REPO/debian jessie main\ndeb $REPO/debian-security jessie/updates main" > /etc/apt/sources.list \
&& apt-get update && apt-get -yq dist-upgrade \
&& apt-get install -yq --no-install-recommends \
build-essential \
cmake \
git-core \
pkg-config \
libjpeg62-turbo-dev \
libtiff5-dev \
libjasper-dev \
libpng12-dev \
libavcodec-dev \
libavformat-dev \
libswscale-dev \
libv4l-dev \
libatlas-base-dev \
gfortran \
tesseract-ocr \
tesseract-ocr-eng \
libtesseract-dev \
libleptonica-dev \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /usr/src/build && cd /usr/src/build \
&& git clone -b $OPENCV_VERSION --depth 1 --recursive https://github.com/opencv/opencv.git \
&& git clone -b $OPENCV_VERSION --depth 1 --recursive https://github.com/opencv/opencv_contrib.git \
&& cd opencv && mkdir build && cd build \
&& cmake \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_C_EXAMPLES=OFF \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D OPENCV_EXTRA_MODULES_PATH=/usr/src/build/opencv_contrib/modules \
-D BUILD_EXAMPLES=OFF \
-D FFMPEG_INCLUDE_DIR=/usr/local/include \
-D FFMPEG_LIB_DIR=/usr/local/lib \
.. \
&& make -j4 install && ldconfig \
&& cd /usr/src/build && rm -rf opencv && rm -rf opencv_contrib \
&& apt-get purge -y cmake && apt-get autoremove -y --purge
# back to unpriviliged user
ENV HOME /home/$NB_USER
| midvalestudent/jupyter | docker/image/Dockerfile | Dockerfile | mit | 3,569 |
<img src="icon.png" alt="Icon" width="128">
NUS Exam Paper Downloader
===============
Simple script to download exam papers from the NUS database. Requires NUSNET login.
Runs on Python 2.7 only.
### Using via Command Line
```
$ python examdownloader-cli.py
```
The required username and target destination can be set in the script or passed as a command line argument.
If no command line arguments are provided, the user is prompted for input.
### Using via a Graphical User Interface
```
$ python examdownloader-gui.py
```
### Compiling the Binary
1. Install `pyinstaller`:
```
$ pip install pyinstaller
```
2. Compile the app:
```
$ pyinstaller build.spec
```
The compiled app can be found inside the `dist` folder.
### Credits
- Oh Shunhao [(https://github.com/Ohohcakester)](https://github.com/Ohohcakester)
- Liu Xinan [(https://github.com/xinan)](https://github.com/xinan)
- Yangshun Tay [(https://github.com/yangshun)](https://github.com/yangshun)
| nusmodifications/nus-exams-downloader | README.md | Markdown | mit | 979 |
module ngFoundation.directives {
//@NgDirective('topBarSection')
class TopBarSectionDirective implements ng.IDirective {
template = '<section class="top-bar-section" ng-transclude></section>';
restrict = "E";
transclude = true;
replace = true;
}
} | rewso/angular-foundation | src/directives/topBarSection.ts | TypeScript | mit | 272 |
# CreditCardValidator
Validate a credit card number with Luhn algorithm.
License: MIT
| supasate/CreditCardValidator | README.md | Markdown | mit | 87 |
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "Three20" do
it "fails" do
fail "hey buddy, you should probably rename this file and start specing for real"
end
end
| jwang/three20-gem | spec/three20_spec.rb | Ruby | mit | 201 |
if (Zepto.ajax.restore) {
Zepto.ajax.restore();
}
sinon.stub(Zepto, "ajax")
.yieldsTo("success", {
responseStatus : 200,
responseDetails : null,
responseData : {
feed: {
link : "http://github.com",
title : "GitHub Public Timeline",
entries : [
{ title : "Croaky signed up",
link : "http://github.com/Croaky/openbeerdatabase",
author : "",
publishedDate : "Thu, 24 Nov 2011 19:00:00 -0600",
content : "\u003cstrong\u003eCroaky\u003c/strong\u003e signed up for GitHub.",
contentSnippet : "Croaky signed up for GitHub.",
categories : []
}
]
}
}
});
| tristandunn/reading | spec/javascripts/fixtures/github.com.js | JavaScript | mit | 753 |
#include "estimation/sensors/make_interpolator.hh"
namespace estimation {
geometry::spatial::TimeInterpolator make_accel_interpolator(
const std::vector<TimedMeasurement<jet_filter::AccelMeasurement>>&
accel_meas,
const ImuModel& imu_model) {
std::vector<geometry::spatial::TimeControlPoint> points;
for (const auto& accel : accel_meas) {
const jcc::Vec3 corrected_accel =
imu_model.correct_measured_accel(accel.measurement.observed_acceleration);
points.push_back({accel.timestamp, corrected_accel});
}
const geometry::spatial::TimeInterpolator interp(points);
return interp;
}
geometry::spatial::TimeInterpolator make_gyro_interpolator(
const std::vector<TimedMeasurement<jet_filter::GyroMeasurement>>&
gyro_meas) {
std::vector<geometry::spatial::TimeControlPoint> points;
for (const auto& gyro : gyro_meas) {
points.push_back({gyro.timestamp, gyro.measurement.observed_w});
}
const geometry::spatial::TimeInterpolator interp(points);
return interp;
}
} // namespace estimation | jpanikulam/experiments | estimation/sensors/make_interpolator.cc | C++ | mit | 1,053 |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import threading
from typing import Optional, Tuple
from pyqrllib.pyqrllib import bin2hstr
from pyqryptonight.pyqryptonight import StringToUInt256, UInt256ToString
from qrl.core import config, BlockHeader
from qrl.core.AddressState import AddressState
from qrl.core.Block import Block
from qrl.core.BlockMetadata import BlockMetadata
from qrl.core.DifficultyTracker import DifficultyTracker
from qrl.core.GenesisBlock import GenesisBlock
from qrl.core.PoWValidator import PoWValidator
from qrl.core.txs.Transaction import Transaction
from qrl.core.txs.CoinBase import CoinBase
from qrl.core.TransactionPool import TransactionPool
from qrl.core.misc import logger
from qrl.crypto.Qryptonight import Qryptonight
from qrl.generated import qrl_pb2, qrlstateinfo_pb2
class ChainManager:
def __init__(self, state):
self._state = state
self.tx_pool = TransactionPool(None)
self._last_block = Block.deserialize(GenesisBlock().serialize())
self.current_difficulty = StringToUInt256(str(config.user.genesis_difficulty))
self.trigger_miner = False
self.lock = threading.RLock()
@property
def height(self):
with self.lock:
if not self._last_block:
return -1
return self._last_block.block_number
@property
def last_block(self) -> Block:
with self.lock:
return self._last_block
@property
def total_coin_supply(self):
with self.lock:
return self._state.total_coin_supply
def get_block_datapoint(self, headerhash):
with self.lock:
return self._state.get_block_datapoint(headerhash)
def get_cumulative_difficulty(self):
with self.lock:
last_block_metadata = self._state.get_block_metadata(self._last_block.headerhash)
return last_block_metadata.cumulative_difficulty
def get_block_by_number(self, block_number) -> Optional[Block]:
with self.lock:
return self._state.get_block_by_number(block_number)
def get_block_header_hash_by_number(self, block_number) -> Optional[bytes]:
with self.lock:
return self._state.get_block_header_hash_by_number(block_number)
def get_block(self, header_hash: bytes) -> Optional[Block]:
with self.lock:
return self._state.get_block(header_hash)
def get_address_balance(self, address: bytes) -> int:
with self.lock:
return self._state.get_address_balance(address)
def get_address_is_used(self, address: bytes) -> bool:
with self.lock:
return self._state.get_address_is_used(address)
def get_address_state(self, address: bytes) -> AddressState:
with self.lock:
return self._state.get_address_state(address)
def get_all_address_state(self):
with self.lock:
return self._state.get_all_address_state()
def get_tx_metadata(self, transaction_hash) -> list:
with self.lock:
return self._state.get_tx_metadata(transaction_hash)
def get_last_transactions(self):
with self.lock:
return self._state.get_last_txs()
def get_unconfirmed_transaction(self, transaction_hash) -> list:
with self.lock:
for tx_set in self.tx_pool.transactions:
tx = tx_set[1].transaction
if tx.txhash == transaction_hash:
return [tx, tx_set[1].timestamp]
if transaction_hash in self.tx_pool.pending_tx_pool_hash:
for tx_set in self.tx_pool.pending_tx_pool:
tx = tx_set[1].transaction
if tx.txhash == transaction_hash:
return [tx, tx_set[1].timestamp]
return []
def get_block_metadata(self, header_hash: bytes) -> Optional[BlockMetadata]:
with self.lock:
return self._state.get_block_metadata(header_hash)
def get_blockheader_and_metadata(self, block_number=0) -> Tuple:
with self.lock:
block_number = block_number or self.height # if both are non-zero, then block_number takes priority
result = (None, None)
block = self.get_block_by_number(block_number)
if block:
blockheader = block.blockheader
blockmetadata = self.get_block_metadata(blockheader.headerhash)
result = (blockheader, blockmetadata)
return result
def get_block_to_mine(self, miner, wallet_address) -> list:
with miner.lock: # Trying to acquire miner.lock to make sure pre_block_logic is not running
with self.lock:
last_block = self.last_block
last_block_metadata = self.get_block_metadata(last_block.headerhash)
return miner.get_block_to_mine(wallet_address,
self.tx_pool,
last_block,
last_block_metadata.block_difficulty)
def get_measurement(self, block_timestamp, parent_headerhash, parent_metadata: BlockMetadata):
with self.lock:
return self._state.get_measurement(block_timestamp, parent_headerhash, parent_metadata)
def get_block_size_limit(self, block: Block):
with self.lock:
return self._state.get_block_size_limit(block)
def get_block_is_duplicate(self, block: Block) -> bool:
with self.lock:
return self._state.get_block(block.headerhash) is not None
def validate_mining_nonce(self, blockheader: BlockHeader, enable_logging=True):
with self.lock:
parent_metadata = self.get_block_metadata(blockheader.prev_headerhash)
parent_block = self._state.get_block(blockheader.prev_headerhash)
measurement = self.get_measurement(blockheader.timestamp, blockheader.prev_headerhash, parent_metadata)
diff, target = DifficultyTracker.get(
measurement=measurement,
parent_difficulty=parent_metadata.block_difficulty)
if enable_logging:
logger.debug('-----------------START--------------------')
logger.debug('Validate #%s', blockheader.block_number)
logger.debug('block.timestamp %s', blockheader.timestamp)
logger.debug('parent_block.timestamp %s', parent_block.timestamp)
logger.debug('parent_block.difficulty %s', UInt256ToString(parent_metadata.block_difficulty))
logger.debug('diff %s', UInt256ToString(diff))
logger.debug('target %s', bin2hstr(target))
logger.debug('-------------------END--------------------')
if not PoWValidator().verify_input(blockheader.mining_blob, target):
if enable_logging:
logger.warning("PoW verification failed")
qn = Qryptonight()
tmp_hash = qn.hash(blockheader.mining_blob)
logger.warning("{}".format(bin2hstr(tmp_hash)))
logger.debug('%s', blockheader.to_json())
return False
return True
def get_headerhashes(self, start_blocknumber):
with self.lock:
start_blocknumber = max(0, start_blocknumber)
end_blocknumber = min(self._last_block.block_number,
start_blocknumber + 2 * config.dev.reorg_limit)
total_expected_headerhash = end_blocknumber - start_blocknumber + 1
node_header_hash = qrl_pb2.NodeHeaderHash()
node_header_hash.block_number = start_blocknumber
block = self._state.get_block_by_number(end_blocknumber)
block_headerhash = block.headerhash
node_header_hash.headerhashes.append(block_headerhash)
end_blocknumber -= 1
while end_blocknumber >= start_blocknumber:
block_metadata = self._state.get_block_metadata(block_headerhash)
for headerhash in block_metadata.last_N_headerhashes[-1::-1]:
node_header_hash.headerhashes.append(headerhash)
end_blocknumber -= len(block_metadata.last_N_headerhashes)
if len(block_metadata.last_N_headerhashes) == 0:
break
block_headerhash = block_metadata.last_N_headerhashes[0]
node_header_hash.headerhashes[:] = node_header_hash.headerhashes[-1::-1]
del node_header_hash.headerhashes[:len(node_header_hash.headerhashes) - total_expected_headerhash]
return node_header_hash
def set_broadcast_tx(self, broadcast_tx):
with self.lock:
self.tx_pool.set_broadcast_tx(broadcast_tx)
def load(self, genesis_block):
# load() has the following tasks:
# Write Genesis Block into State immediately
# Register block_number <-> blockhash mapping
# Calculate difficulty Metadata for Genesis Block
# Generate AddressStates from Genesis Block balances
# Apply Genesis Block's transactions to the state
# Detect if we are forked from genesis block and if so initiate recovery.
height = self._state.get_mainchain_height()
if height == -1:
self._state.put_block(genesis_block, None)
block_number_mapping = qrl_pb2.BlockNumberMapping(headerhash=genesis_block.headerhash,
prev_headerhash=genesis_block.prev_headerhash)
self._state.put_block_number_mapping(genesis_block.block_number, block_number_mapping, None)
parent_difficulty = StringToUInt256(str(config.user.genesis_difficulty))
self.current_difficulty, _ = DifficultyTracker.get(
measurement=config.dev.mining_setpoint_blocktime,
parent_difficulty=parent_difficulty)
block_metadata = BlockMetadata.create()
block_metadata.set_block_difficulty(self.current_difficulty)
block_metadata.set_cumulative_difficulty(self.current_difficulty)
self._state.put_block_metadata(genesis_block.headerhash, block_metadata, None)
addresses_state = dict()
for genesis_balance in GenesisBlock().genesis_balance:
bytes_addr = genesis_balance.address
addresses_state[bytes_addr] = AddressState.get_default(bytes_addr)
addresses_state[bytes_addr]._data.balance = genesis_balance.balance
for tx_idx in range(1, len(genesis_block.transactions)):
tx = Transaction.from_pbdata(genesis_block.transactions[tx_idx])
for addr in tx.addrs_to:
addresses_state[addr] = AddressState.get_default(addr)
coinbase_tx = Transaction.from_pbdata(genesis_block.transactions[0])
if not isinstance(coinbase_tx, CoinBase):
return False
addresses_state[coinbase_tx.addr_to] = AddressState.get_default(coinbase_tx.addr_to)
if not coinbase_tx.validate_extended(genesis_block.block_number):
return False
coinbase_tx.apply_state_changes(addresses_state)
for tx_idx in range(1, len(genesis_block.transactions)):
tx = Transaction.from_pbdata(genesis_block.transactions[tx_idx])
tx.apply_state_changes(addresses_state)
self._state.put_addresses_state(addresses_state)
self._state.update_tx_metadata(genesis_block, None)
self._state.update_mainchain_height(0, None)
else:
self._last_block = self.get_block_by_number(height)
self.current_difficulty = self._state.get_block_metadata(self._last_block.headerhash).block_difficulty
fork_state = self._state.get_fork_state()
if fork_state:
block = self._state.get_block(fork_state.initiator_headerhash)
self._fork_recovery(block, fork_state)
def _apply_block(self, block: Block, batch) -> bool:
address_set = self._state.prepare_address_list(block) # Prepare list for current block
addresses_state = self._state.get_state_mainchain(address_set)
if not block.apply_state_changes(addresses_state):
return False
self._state.put_addresses_state(addresses_state, batch)
return True
def _update_chainstate(self, block: Block, batch):
self._last_block = block
self._update_block_number_mapping(block, batch)
self.tx_pool.remove_tx_in_block_from_pool(block)
self._state.update_mainchain_height(block.block_number, batch)
self._state.update_tx_metadata(block, batch)
def _try_branch_add_block(self, block, batch, check_stale=True) -> (bool, bool):
"""
This function returns list of bool types. The first bool represent
if the block has been added successfully and the second bool
represent the fork_flag, which becomes true when a block triggered
into fork recovery.
:param block:
:param batch:
:return: [Added successfully, fork_flag]
"""
if self._last_block.headerhash == block.prev_headerhash:
if not self._apply_block(block, batch):
return False, False
self._state.put_block(block, batch)
last_block_metadata = self._state.get_block_metadata(self._last_block.headerhash)
if last_block_metadata is None:
logger.warning("Could not find log metadata for %s", bin2hstr(self._last_block.headerhash))
return False, False
last_block_difficulty = int(UInt256ToString(last_block_metadata.cumulative_difficulty))
new_block_metadata = self._add_block_metadata(block.headerhash, block.timestamp, block.prev_headerhash, batch)
new_block_difficulty = int(UInt256ToString(new_block_metadata.cumulative_difficulty))
if new_block_difficulty > last_block_difficulty:
if self._last_block.headerhash != block.prev_headerhash:
fork_state = qrlstateinfo_pb2.ForkState(initiator_headerhash=block.headerhash)
self._state.put_fork_state(fork_state, batch)
self._state.write_batch(batch)
return self._fork_recovery(block, fork_state), True
self._update_chainstate(block, batch)
if check_stale:
self.tx_pool.check_stale_txn(self._state, block.block_number)
self.trigger_miner = True
return True, False
def _remove_block_from_mainchain(self, block: Block, latest_block_number: int, batch):
addresses_set = self._state.prepare_address_list(block)
addresses_state = self._state.get_state_mainchain(addresses_set)
for tx_idx in range(len(block.transactions) - 1, -1, -1):
tx = Transaction.from_pbdata(block.transactions[tx_idx])
tx.revert_state_changes(addresses_state, self)
self.tx_pool.add_tx_from_block_to_pool(block, latest_block_number)
self._state.update_mainchain_height(block.block_number - 1, batch)
self._state.rollback_tx_metadata(block, batch)
self._state.remove_blocknumber_mapping(block.block_number, batch)
self._state.put_addresses_state(addresses_state, batch)
def _get_fork_point(self, block: Block):
tmp_block = block
hash_path = []
while True:
if not block:
raise Exception('[get_state] No Block Found %s, Initiator %s', block.headerhash, tmp_block.headerhash)
mainchain_block = self.get_block_by_number(block.block_number)
if mainchain_block and mainchain_block.headerhash == block.headerhash:
break
if block.block_number == 0:
raise Exception('[get_state] Alternate chain genesis is different, Initiator %s', tmp_block.headerhash)
hash_path.append(block.headerhash)
block = self._state.get_block(block.prev_headerhash)
return block.headerhash, hash_path
def _rollback(self, forked_header_hash: bytes, fork_state: qrlstateinfo_pb2.ForkState = None):
"""
Rollback from last block to the block just before the forked_header_hash
:param forked_header_hash:
:param fork_state:
:return:
"""
hash_path = []
while self._last_block.headerhash != forked_header_hash:
block = self._state.get_block(self._last_block.headerhash)
mainchain_block = self._state.get_block_by_number(block.block_number)
if block is None:
logger.warning("self.state.get_block(self.last_block.headerhash) returned None")
if mainchain_block is None:
logger.warning("self.get_block_by_number(block.block_number) returned None")
if block.headerhash != mainchain_block.headerhash:
break
hash_path.append(self._last_block.headerhash)
batch = self._state.batch
self._remove_block_from_mainchain(self._last_block, block.block_number, batch)
if fork_state:
fork_state.old_mainchain_hash_path.extend([self._last_block.headerhash])
self._state.put_fork_state(fork_state, batch)
self._state.write_batch(batch)
self._last_block = self._state.get_block(self._last_block.prev_headerhash)
return hash_path
def add_chain(self, hash_path: list, fork_state: qrlstateinfo_pb2.ForkState) -> bool:
"""
Add series of blocks whose headerhash mentioned into hash_path
:param hash_path:
:param fork_state:
:param batch:
:return:
"""
with self.lock:
start = 0
try:
start = hash_path.index(self._last_block.headerhash) + 1
except ValueError:
# Following condition can only be true if the fork recovery was interrupted last time
if self._last_block.headerhash in fork_state.old_mainchain_hash_path:
return False
for i in range(start, len(hash_path)):
header_hash = hash_path[i]
block = self._state.get_block(header_hash)
batch = self._state.batch
if not self._apply_block(block, batch):
return False
self._update_chainstate(block, batch)
logger.debug('Apply block #%d - [batch %d | %s]', block.block_number, i, hash_path[i])
self._state.write_batch(batch)
self._state.delete_fork_state()
return True
def _fork_recovery(self, block: Block, fork_state: qrlstateinfo_pb2.ForkState) -> bool:
logger.info("Triggered Fork Recovery")
# This condition only becomes true, when fork recovery was interrupted
if fork_state.fork_point_headerhash:
logger.info("Recovering from last fork recovery interruption")
forked_header_hash, hash_path = fork_state.fork_point_headerhash, fork_state.new_mainchain_hash_path
else:
forked_header_hash, hash_path = self._get_fork_point(block)
fork_state.fork_point_headerhash = forked_header_hash
fork_state.new_mainchain_hash_path.extend(hash_path)
self._state.put_fork_state(fork_state)
rollback_done = False
if fork_state.old_mainchain_hash_path:
b = self._state.get_block(fork_state.old_mainchain_hash_path[-1])
if b and b.prev_headerhash == fork_state.fork_point_headerhash:
rollback_done = True
if not rollback_done:
logger.info("Rolling back")
old_hash_path = self._rollback(forked_header_hash, fork_state)
else:
old_hash_path = fork_state.old_mainchain_hash_path
if not self.add_chain(hash_path[-1::-1], fork_state):
logger.warning("Fork Recovery Failed... Recovering back to old mainchain")
# If above condition is true, then it means, the node failed to add_chain
# Thus old chain state, must be retrieved
self._rollback(forked_header_hash)
self.add_chain(old_hash_path[-1::-1], fork_state) # Restores the old chain state
return False
logger.info("Fork Recovery Finished")
self.trigger_miner = True
return True
def _add_block(self, block, batch=None, check_stale=True) -> (bool, bool):
self.trigger_miner = False
block_size_limit = self.get_block_size_limit(block)
if block_size_limit and block.size > block_size_limit:
logger.info('Block Size greater than threshold limit %s > %s', block.size, block_size_limit)
return False, False
return self._try_branch_add_block(block, batch, check_stale)
def add_block(self, block: Block, check_stale=True) -> bool:
with self.lock:
if block.block_number < self.height - config.dev.reorg_limit:
logger.debug('Skipping block #%s as beyond re-org limit', block.block_number)
return False
if self.get_block_is_duplicate(block):
return False
batch = self._state.batch
block_flag, fork_flag = self._add_block(block, batch=batch, check_stale=check_stale)
if block_flag:
if not fork_flag:
self._state.write_batch(batch)
logger.info('Added Block #%s %s', block.block_number, bin2hstr(block.headerhash))
return True
return False
def _add_block_metadata(self,
headerhash,
block_timestamp,
parent_headerhash,
batch):
block_metadata = self._state.get_block_metadata(headerhash)
if not block_metadata:
block_metadata = BlockMetadata.create()
parent_metadata = self._state.get_block_metadata(parent_headerhash)
parent_block_difficulty = parent_metadata.block_difficulty
parent_cumulative_difficulty = parent_metadata.cumulative_difficulty
block_metadata.update_last_headerhashes(parent_metadata.last_N_headerhashes, parent_headerhash)
measurement = self._state.get_measurement(block_timestamp, parent_headerhash, parent_metadata)
block_difficulty, _ = DifficultyTracker.get(
measurement=measurement,
parent_difficulty=parent_block_difficulty)
block_cumulative_difficulty = StringToUInt256(str(
int(UInt256ToString(block_difficulty)) +
int(UInt256ToString(parent_cumulative_difficulty))))
block_metadata.set_block_difficulty(block_difficulty)
block_metadata.set_cumulative_difficulty(block_cumulative_difficulty)
parent_metadata.add_child_headerhash(headerhash)
self._state.put_block_metadata(parent_headerhash, parent_metadata, batch)
self._state.put_block_metadata(headerhash, block_metadata, batch)
return block_metadata
def _update_block_number_mapping(self, block, batch):
block_number_mapping = qrl_pb2.BlockNumberMapping(headerhash=block.headerhash,
prev_headerhash=block.prev_headerhash)
self._state.put_block_number_mapping(block.block_number, block_number_mapping, batch)
| jleni/QRL | src/qrl/core/ChainManager.py | Python | mit | 23,847 |
<?php
namespace Nitrapi\Common\Exceptions;
class NitrapiHttpErrorException extends NitrapiException
{
} | nitrado/Nitrapi-PHP | lib/Nitrapi/Common/Exceptions/NitrapiHttpErrorException.php | PHP | mit | 105 |
var baseURL;
$.validator.addMethod("alfanumerico", function(value, element) {
return this.optional(element) || /^[-._a-z0-9\- ]+$/i.test(value);
}, "Este campo es alfanumerico.");
$("#frmGuardaTipoDocumento").validate({
rules : {
descripcion : "required",
codigo : {required:true,alfanumerico:true},
},
messages : {
descripcion : "Ingrese este campo.",
codigo : {required:"Ingrese este campo.",alfanumerico:"Este campo es alfanumerico."},
},
submitHandler : function(form) {
$.ajax(form.action, {
async : false,
type : "POST",
data : $(form).serialize(),
success : function(contenido) {
//alert("contenido :"+ contenido);
if(contenido=="error"){
var mensaje="Este tipo de documento ya ha sido registrado";
alert(mensaje);
}
else{
baseURL = $("#baseURL").val();
$.get(baseURL + "mantenimientoInterno/listarTiposDocumentos?info="+contenido, function(respuesta) {
$("#contenidoPrincipal").html(respuesta);
$("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado");
});
}
}
});
}
});
function cancelarTipoDocumento(){
var baseURL;
baseURL = $("#baseURL").val();
$("#contenidoPrincipal").html("Cargando . . .");
$.get(baseURL + "mantenimientoInterno/listarTiposDocumentos", function(respuesta) {
$("#contenidoPrincipal").html(respuesta);
$("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado");
});
}
| javiervilcapaza/inst | inst/src/main/webapp/resources/scripts/mantenimientoInterno/tipoDocumentoFormulario.js | JavaScript | mit | 1,492 |
export { default } from 'ember-flexberry-designer/controllers/fd-interface-edit-form/new';
| Flexberry/ember-flexberry-designer | app/controllers/fd-interface-edit-form/new.js | JavaScript | mit | 91 |
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
//Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
//});
//Route::get('wechat/index', 'WechatController@index');
| growu/growu-website | routes/api.php | PHP | mit | 591 |
Symfony Standard Edition
========================
Welcome to the Symfony Standard Edition - a fully-functional Symfony2
application that you can use as the skeleton for your new applications.
This document contains information on how to download, install, and start
using Symfony. For a more detailed explanation, see the [Installation][1]
chapter of the Symfony Documentation.
1) Installing the Standard Edition
----------------------------------
When it comes to installing the Symfony Standard Edition, you have the
following options.
### Use Composer (*recommended*)
As Symfony uses [Composer][2] to manage its dependencies, the recommended way
to create a new project is to use it.
If you don't have Composer yet, download it following the instructions on
http://getcomposer.org/ or just run the following command:
curl -s http://getcomposer.org/installer | php
Then, use the `create-project` command to generate a new Symfony application:
php composer.phar create-project symfony/framework-standard-edition path/to/install
Composer will install Symfony and all its dependencies under the
`path/to/install` directory.
### Download an Archive File
To quickly test Symfony, you can also download an [archive][3] of the Standard
Edition and unpack it somewhere under your web server root directory.
If you downloaded an archive "without vendors", you also need to install all
the necessary dependencies. Download composer (see above) and run the
following command:
php composer.phar install
2) Checking your System Configuration
-------------------------------------
Before starting coding, make sure that your local system is properly
configured for Symfony.
Execute the `check.php` script from the command line:
php app/check.php
The script returns a status code of `0` if all mandatory requirements are met,
`1` otherwise.
Access the `config.php` script from a browser:
http://localhost/path/to/symfony/app/web/config.php
If you get any warnings or recommendations, fix them before moving on.
3) Browsing the Demo Application
--------------------------------
Congratulations! You're now ready to use Symfony.
From the `config.php` page, click the "Bypass configuration and go to the
Welcome page" link to load up your first Symfony page.
You can also use a web-based configurator by clicking on the "Configure your
Symfony Application online" link of the `config.php` page.
To see a real-live Symfony page in action, access the following page:
web/app_dev.php/demo/hello/Fabien
4) Getting started with Symfony
-------------------------------
This distribution is meant to be the starting point for your Symfony
applications, but it also contains some sample code that you can learn from
and play with.
A great way to start learning Symfony is via the [Quick Tour][4], which will
take you through all the basic features of Symfony2.
Once you're feeling good, you can move onto reading the official
[Symfony2 book][5].
A default bundle, `AcmeDemoBundle`, shows you Symfony2 in action. After
playing with it, you can remove it by following these steps:
* delete the `src/Acme` directory;
* remove the routing entry referencing AcmeDemoBundle in `app/config/routing_dev.yml`;
* remove the AcmeDemoBundle from the registered bundles in `app/AppKernel.php`;
* remove the `web/bundles/acmedemo` directory;
* remove the `security.providers`, `security.firewalls.login` and
`security.firewalls.secured_area` entries in the `security.yml` file or
tweak the security configuration to fit your needs.
What's inside?
---------------
The Symfony Standard Edition is configured with the following defaults:
* Twig is the only configured template engine;
* Doctrine ORM/DBAL is configured;
* Swiftmailer is configured;
* Annotations for everything are enabled.
It comes pre-configured with the following bundles:
* **FrameworkBundle** - The core Symfony framework bundle
* [**SensioFrameworkExtraBundle**][6] - Adds several enhancements, including
template and routing annotation capability
* [**DoctrineBundle**][7] - Adds support for the Doctrine ORM
* [**TwigBundle**][8] - Adds support for the Twig templating engine
* [**SecurityBundle**][9] - Adds security by integrating Symfony's security
component
* [**SwiftmailerBundle**][10] - Adds support for Swiftmailer, a library for
sending emails
* [**MonologBundle**][11] - Adds support for Monolog, a logging library
* [**AsseticBundle**][12] - Adds support for Assetic, an asset processing
library
* **WebProfilerBundle** (in dev/test env) - Adds profiling functionality and
the web debug toolbar
* **SensioDistributionBundle** (in dev/test env) - Adds functionality for
configuring and working with Symfony distributions
* [**SensioGeneratorBundle**][13] (in dev/test env) - Adds code generation
capabilities
* **AcmeDemoBundle** (in dev/test env) - A demo bundle with some example
code
All libraries and bundles included in the Symfony Standard Edition are
released under the MIT or BSD license.
Enjoy!
[1]: http://symfony.com/doc/2.3/book/installation.html
[2]: http://getcomposer.org/
[3]: http://symfony.com/download
[4]: http://symfony.com/doc/2.3/quick_tour/the_big_picture.html
[5]: http://symfony.com/doc/2.3/index.html
[6]: http://symfony.com/doc/2.3/bundles/SensioFrameworkExtraBundle/index.html
[7]: http://symfony.com/doc/2.3/book/doctrine.html
[8]: http://symfony.com/doc/2.3/book/templating.html
[9]: http://symfony.com/doc/2.3/book/security.html
[10]: http://symfony.com/doc/2.3/cookbook/email.html
[11]: http://symfony.com/doc/2.3/cookbook/logging/monolog.html
[12]: http://symfony.com/doc/2.3/cookbook/assetic/asset_management.html
[13]: http://symfony.com/doc/2.3/bundles/SensioGeneratorBundle/index.html
# Kifland
| KroKroDile/Kifland | README.md | Markdown | mit | 5,853 |
#ifndef _ZLX_PLATFORM_H
#define _ZLX_PLATFORM_H
#include "arch.h"
#if defined(ZLX_FREESTANDING) && ZLX_FREESTANDING
#else
# undef ZLX_FREESTANDING
# define ZLX_FREESTANDING 0
# if defined(_WIN32)
# define ZLX_MSWIN 1
# elif defined(_AIX)
# define ZLX_AIX 1
# elif defined(__unix__) || defined(__unix)
# define ZLX_UNIX 1
# include <unistd.h>
# if defined(POSIX_VERSION)
# define ZLX_POSIX POSIX_VERSION
# endif
# if defined(__DragonFly__)
# define ZLX_BSD 1
# define ZLX_DRAGONFLY_BSD 1
# elif defined(__FreeBSD__)
# define ZLX_BSD 1
# define ZLX_FREEBSD 1
# elif defined(__NetBSD__)
# define ZLX_BSD 1
# define ZLX_NETBSD 1
# elif defined(__OpenBSD__)
# define ZLX_BSD 1
# define ZLX_OPENBSD 1
# endif
# endif /* OS defines */
#endif /* ZLX_FREESTANDING */
/* assume System V ABI if we're not under a Microsoft environment */
#if !defined(ZLX_ABI_SYSV) && !defined(ZLX_ABI_MS)
# if defined(_WIN32)
# define ZLX_ABI_MS 1
# else
# define ZLX_ABI_SYSV 1
# endif
#endif
#if ZLX_IA32 && ZLX_ABI_MS
# define ZLX_FAST_CALL __fastcall
#elif ZLX_IA32 && ZLX_ABI_SYSV && (ZLX_GCC || ZLX_CLANG)
# define ZLX_FAST_CALL __attribute__((regparm((3))))
#else
# define ZLX_FAST_CALL
#endif
#endif /* _ZLX_PLATFORM_H */
| icostin/zlx | include/zlx/platform.h | C | mit | 1,255 |
## Rails 5.0.4 (June 19, 2017) ##
* Fix regression in numericality validator when comparing Decimal and Float input
values with more scale than the schema.
*Bradley Priest*
## Rails 5.0.3 (May 12, 2017) ##
* The original string assigned to a model attribute is no longer incorrectly
frozen.
Fixes #24185, #28718.
*Matthew Draper*
* Avoid converting integer as a string into float.
*namusyaka*
## Rails 5.0.2 (March 01, 2017) ##
* No changes.
## Rails 5.0.1 (December 21, 2016) ##
* No changes.
## Rails 5.0.1.rc2 (December 10, 2016) ##
* No changes.
## Rails 5.0.1.rc1 (December 01, 2016) ##
* Fix `Type::Date#serialize` to cast a value to a date object properly.
This casting fixes queries for finding records by date column.
Fixes #25354.
*Ryuta Kamizono*
## Rails 5.0.0 (June 30, 2016) ##
* `Dirty`'s `*_changed?` methods now return an actual singleton, never `nil`, as in 4.2.
Fixes #24220.
*Sen-Zhang*
* Ensure that instances of `ActiveModel::Errors` can be marshalled.
Fixes #25165.
*Sean Griffin*
* Allow passing record being validated to the message proc to generate
customized error messages for that object using I18n helper.
*Prathamesh Sonpatki*
* Validate multiple contexts on `valid?` and `invalid?` at once.
Example:
class Person
include ActiveModel::Validations
attr_reader :name, :title
validates_presence_of :name, on: :create
validates_presence_of :title, on: :update
end
person = Person.new
person.valid?([:create, :update]) # => false
person.errors.messages # => {:name=>["can't be blank"], :title=>["can't be blank"]}
*Dmitry Polushkin*
* Add case_sensitive option for confirmation validator in models.
*Akshat Sharma*
* Ensure `method_missing` is called for methods passed to
`ActiveModel::Serialization#serializable_hash` that don't exist.
*Jay Elaraj*
* Remove `ActiveModel::Serializers::Xml` from core.
*Zachary Scott*
* Add `ActiveModel::Dirty#[attr_name]_previously_changed?` and
`ActiveModel::Dirty#[attr_name]_previous_change` to improve access
to recorded changes after the model has been saved.
It makes the dirty-attributes query methods consistent before and after
saving.
*Fernando Tapia Rico*
* Deprecate the `:tokenizer` option for `validates_length_of`, in favor of
plain Ruby.
*Sean Griffin*
* Deprecate `ActiveModel::Errors#add_on_empty` and `ActiveModel::Errors#add_on_blank`
with no replacement.
*Wojciech Wnętrzak*
* Deprecate `ActiveModel::Errors#get`, `ActiveModel::Errors#set` and
`ActiveModel::Errors#[]=` methods that have inconsistent behavior.
*Wojciech Wnętrzak*
* Allow symbol as values for `tokenize` of `LengthValidator`.
*Kensuke Naito*
* Assigning an unknown attribute key to an `ActiveModel` instance during initialization
will now raise `ActiveModel::AttributeAssignment::UnknownAttributeError` instead of
`NoMethodError`.
Example:
User.new(foo: 'some value')
# => ActiveModel::AttributeAssignment::UnknownAttributeError: unknown attribute 'foo' for User.
*Eugene Gilburg*
* Extracted `ActiveRecord::AttributeAssignment` to `ActiveModel::AttributeAssignment`
allowing to use it for any object as an includable module.
Example:
class Cat
include ActiveModel::AttributeAssignment
attr_accessor :name, :status
end
cat = Cat.new
cat.assign_attributes(name: "Gorby", status: "yawning")
cat.name # => 'Gorby'
cat.status # => 'yawning'
cat.assign_attributes(status: "sleeping")
cat.name # => 'Gorby'
cat.status # => 'sleeping'
*Bogdan Gusiev*
* Add `ActiveModel::Errors#details`
To be able to return type of used validator, one can now call `details`
on errors instance.
Example:
class User < ActiveRecord::Base
validates :name, presence: true
end
user = User.new; user.valid?; user.errors.details
=> {name: [{error: :blank}]}
*Wojciech Wnętrzak*
* Change `validates_acceptance_of` to accept `true` by default besides `'1'`.
The default for `validates_acceptance_of` is now `'1'` and `true`.
In the past, only `"1"` was the default and you were required to pass
`accept: true` separately.
*mokhan*
* Remove deprecated `ActiveModel::Dirty#reset_#{attribute}` and
`ActiveModel::Dirty#reset_changes`.
*Rafael Mendonça França*
* Change the way in which callback chains can be halted.
The preferred method to halt a callback chain from now on is to explicitly
`throw(:abort)`.
In the past, returning `false` in an Active Model `before_` callback had
the side effect of halting the callback chain.
This is not recommended anymore and, depending on the value of the
`ActiveSupport.halt_callback_chains_on_return_false` option, will
either not work at all or display a deprecation warning.
*claudiob*
Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activemodel/CHANGELOG.md) for previous changes.
| best-summer/project-dystopia | api-server/vendor/bundle/gems/activemodel-5.0.4/CHANGELOG.md | Markdown | mit | 5,282 |
---
title: Color Palette
layout: page
description: taCss color palette same as the Material Design Lite color palette.
utilities: true
---
<div class="row p-3">
<h6>color setup</h6>
<div class="code col-12 info p-3 m-b-3">
{% highlight scss %}
/* colors setups in "core/_variables.scss" */
/* enable/disable the default colors for components */
$enable-colors: true !default;
/* don't forget include minimum the primary and the accent color */
/* the palette variables can be found in the "core/_colorpalette.scss" */
$primary-palette: $teal-palette !default;
$accent-palette: $deep-orange-palette !default;
$enable--red-palette: true !default;
$enable--pink-palette: true !default;
$enable--purple-palette: true !default;
$enable--deep-purple-palette: true !default;
$enable--indigo-palette: true !default;
$enable--blue-palette: true !default;
$enable--light-blue-palette: true !default;
$enable--cyan-palette: true !default;
$enable--teal-palette: true !default;
$enable--green-palette: true !default;
$enable--light-green-palette: true !default;
$enable--lime-palette: true !default;
$enable--yellow-palette: true !default;
$enable--amber-palette: true !default;
$enable--orange-palette: true !default;
$enable--deep-orange-palette: true !default;
$enable--brown-palette: true !default;
$enable--grey-palette: true !default;
$enable--blue-grey-palette: true !default;
$enable--black-palette: true !default;
$enable--white-palette: true !default;
/* basic palette contains black, white and the midle colors for the rest even if the color-palette not enabled. no accent color. */
$enable--basic-palette: true !default;
{% endhighlight %}
</div>
<h6>background</h6>
<p>
Use the <span class="code-class">bg-</span> prefix with your <i>color</i> of choice.
</p>
<p class="col-6 col-t-8 ">
<button class='btn bg-red'> red </button>
<button class='btn bg-pink'> pink </button>
<button class='btn bg-purple'> purple </button>
<button class='btn bg-deep-purple'> deep-purple </button>
<button class='btn bg-indigo'> indigo </button>
<button class='btn bg-blue'> blue </button>
<button class='btn bg-light-blue'> light-blue </button>
<button class='btn bg-lime'> lime </button>
<button class='btn bg-yellow'> yellow </button>
<button class='btn bg-amber'> amber </button>
<button class='btn bg-orange'> orange </button>
<button class='btn bg-deep-orange'> deep-orange </button>
<button class='btn bg-brown'> brown </button>
<button class='btn bg-grey'> grey </button>
<button class='btn bg-blue-grey'> blue-grey </button>
<button class='btn bg-black'> black </button>
<button class='btn bg-white'> white </button>
</p>
<div class="code info code-large col-6 col-t-8">
{% highlight html %}
<button class='btn bg-red'> red </button>
<button class='btn bg-pink'> pink </button>
<button class='btn bg-purple'> purple </button>
<button class='btn bg-deep-purple'> deep-purple </button>
<button class='btn bg-indigo'> indigo </button>
<button class='btn bg-blue'> blue </button>
<button class='btn bg-light-blue'> light-blue </button>
<button class='btn bg-lime'> lime </button>
<button class='btn bg-yellow'> yellow </button>
<button class='btn bg-amber'> amber </button>
<button class='btn bg-orange'> orange </button>
<button class='btn bg-deep-orange'> deep-orange </button>
<button class='btn bg-brown'> brown </button>
<button class='btn bg-grey'> grey </button>
<button class='btn bg-blue-grey'> blue-grey </button>
<button class='btn bg-black'> black </button>
<button class='btn bg-white'> white </button>
{% endhighlight %}
</div>
<h6>auto textcolor</h6>
<p>
To choose readable font color automatic to the choosen background use the <span class="code-class">colored</span> class.
</p>
<p class="col-6 col-t-8 ">
<button class='colored btn bg-red'> red </button>
<button class='colored btn bg-pink'> pink </button>
<button class='colored btn bg-purple'> purple </button>
<button class='colored btn bg-deep-purple'> deep-purple </button>
<button class='colored btn bg-indigo'> indigo </button>
<button class='colored btn bg-blue'> blue </button>
<button class='colored btn bg-light-blue'> light-blue </button>
<button class='colored btn bg-lime'> lime </button>
<button class='colored btn bg-yellow'> yellow </button>
<button class='colored btn bg-amber'> amber </button>
<button class='colored btn bg-orange'> orange </button>
<button class='colored btn bg-deep-orange'> deep-orange </button>
<button class='colored btn bg-brown'> brown </button>
<button class='colored btn bg-grey'> grey </button>
<button class='colored btn bg-blue-grey'> blue-grey </button>
<button class='colored btn bg-black'> black </button>
<button class='colored btn bg-white'> white </button>
</p>
<div class="code info code-large col-6 col-t-8">
{% highlight html %}
<button class='colored btn bg-red'> red </button>
<button class='colored btn bg-pink'> pink </button>
<button class='colored btn bg-purple'> purple </button>
<button class='colored btn bg-deep-purple'> deep-purple </button>
<button class='colored btn bg-indigo'> indigo </button>
<button class='colored btn bg-blue'> blue </button>
<button class='colored btn bg-light-blue'> light-blue </button>
<button class='colored btn bg-lime'> lime </button>
<button class='colored btn bg-yellow'> yellow </button>
<button class='colored btn bg-amber'> amber </button>
<button class='colored btn bg-orange'> orange </button>
<button class='colored btn bg-deep-orange'> deep-orange </button>
<button class='colored btn bg-brown'> brown </button>
<button class='colored btn bg-grey'> grey </button>
<button class='colored btn bg-blue-grey'> blue-grey </button>
<button class='colored btn bg-black'> black </button>
<button class='colored btn bg-white'> white </button>
{% endhighlight %}
</div>
<h6>outline (border and text color)</h6>
<p>
Use the <span class="code-class">outline-</span> prefix with your <i>color</i> of choice to get colored border and text.
</p>
<p class="col-6 col-t-9">
<button class='btn outline-red'> red </button>
<button class='btn outline-pink'> pink </button>
<button class='btn outline-purple'> purple </button>
<button class='btn outline-deep-purple'> deep-purple </button>
<button class='btn outline-indigo'> indigo </button>
<button class='btn outline-blue'> blue </button>
<button class='btn outline-light-blue'> light-blue </button>
<button class='btn outline-lime'> lime </button>
<button class='btn outline-yellow'> yellow </button>
<button class='btn outline-amber'> amber </button>
<button class='btn outline-orange'> orange </button>
<button class='btn outline-deep-orange'> deep-orange </button>
<button class='btn outline-brown'> brown </button>
<button class='btn outline-grey'> grey </button>
<button class='btn outline-blue-grey'> blue-grey </button>
<button class='btn outline-black'> black </button>
<button class='btn outline-white'> white </button>
</p>
<div class="code info code-large col-6 col-t-8">
{% highlight html %}
<button class='btn outline-red'> red </button>
<button class='btn outline-pink'> pink </button>
<button class='btn outline-purple'> purple </button>
<button class='btn outline-deep-purple'> deep-purple </button>
<button class='btn outline-indigo'> indigo </button>
<button class='btn outline-blue'> blue </button>
<button class='btn outline-light-blue'> light-blue </button>
<button class='btn outline-lime'> lime </button>
<button class='btn outline-yellow'> yellow </button>
<button class='btn outline-amber'> amber </button>
<button class='btn outline-orange'> orange </button>
<button class='btn outline-deep-orange'> deep-orange </button>
<button class='btn outline-brown'> brown </button>
<button class='btn outline-grey'> grey </button>
<button class='btn outline-blue-grey'> blue-grey </button>
<button class='btn outline-black'> black </button>
<button class='btn outline-white'> white </button>
{% endhighlight %}
</div>
<h6>text color</h6>
<p>
Use the <span class="code-class">text-</span> prefix with your <i>color</i> of choice to get colored text.
</p>
<p class="col-6 col-t-8">
<button class='btn text-red'> red </button>
<button class='btn text-pink'> pink </button>
<button class='btn text-purple'> purple </button>
<button class='btn text-deep-purple'> deep-purple </button>
<button class='btn text-indigo'> indigo </button>
<button class='btn text-blue'> blue </button>
<button class='btn text-light-blue'> light-blue </button>
<button class='btn text-lime'> lime </button>
<button class='btn text-yellow'> yellow </button>
<button class='btn text-amber'> amber </button>
<button class='btn text-orange'> orange </button>
<button class='btn text-deep-orange'> deep-orange </button>
<button class='btn text-brown'> brown </button>
<button class='btn text-grey'> grey </button>
<button class='btn text-blue-grey'> blue-grey </button>
<button class='btn text-black'> black </button>
<button class='btn text-white'> white </button>
</p>
<div class="code info code-large col-6 col-t-8">
{% highlight html %}
<button class='btn text-red'> red </button>
<button class='btn text-pink'> pink </button>
<button class='btn text-purple'> purple </button>
<button class='btn text-deep-purple'> deep-purple </button>
<button class='btn text-indigo'> indigo </button>
<button class='btn text-blue'> blue </button>
<button class='btn text-light-blue'> light-blue </button>
<button class='btn text-lime'> lime </button>
<button class='btn text-yellow'> yellow </button>
<button class='btn text-amber'> amber </button>
<button class='btn text-orange'> orange </button>
<button class='btn text-deep-orange'> deep-orange </button>
<button class='btn text-brown'> brown </button>
<button class='btn text-grey'> grey </button>
<button class='btn text-blue-grey'> blue-grey </button>
<button class='btn text-black'> black </button>
<button class='btn text-white'> white </button>
{% endhighlight %}
</div>
<h6>the full color palette</h6>
<div class="row" id="colorPalettesBlock">
</div>
<div class="row" id=textColorPalettesBlock>
</div>
<script type="text/javascript">
var basicPalette = [
"red", "pink", "purple", "deep-purple", "indigo", "blue", "light-blue", "lime",
"yellow", "amber", "orange", "deep-orange", "brown", "grey", "blue-grey", "black", "white",
];
var redPalette = ['red-0','red-1','red-2','red-3','red-4','red','red-6','red-7','red-8','red-9','red-a1','red-a2','red-a3','red-a4'];
var pinkPalette = ['pink-0','pink-1','pink-2','pink-3','pink-4','pink','pink-6','pink-7','pink-8','pink-9','pink-a1','pink-a2','pink-a3','pink-a4'];
var purplePalette = ['purple-0','purple-1','purple-2','purple-3','purple-4','purple','purple-6','purple-7','purple-8','purple-9','purple-a1','purple-a2','purple-a3','purple-a4'];
var deepPurplePalette = ['deep-purple-0','deep-purple-1','deep-purple-2','deep-purple-3','deep-purple-4','deep-purple','deep-purple-6','deep-purple-7','deep-purple-8','deep-purple-9','deep-purple-a1','deep-purple-a2','deep-purple-a3','deep-purple-a3'];
var indigoPalette = ['indigo-0','indigo-1','indigo-2','indigo-3','indigo-4','indigo','indigo-6','indigo-7','indigo-8','indigo-9','indigo-a1','indigo-a2','indigo-a3','indigo-a4'];
var bluePalette = ['blue-0','blue-1','blue-2','blue-3','blue-4','blue','blue-6','blue-7','blue-8','blue-9','blue-a1','blue-a2','blue-a3','blue-a4'];
var lightBluePalette = ['light-blue-0','light-blue-1','light-blue-2','light-blue-3','light-blue-4','light-blue','light-blue-6','light-blue-7','light-blue-8','light-blue-9','light-blue-a1','light-blue-a2','light-blue-a3','light-blue-a4'];
var cyanPalette = ['cyan-0','cyan-1','cyan-2','cyan-3','cyan-4','cyan','cyan-6','cyan-7','cyan-8','cyan-9','cyan-a1','cyan-a2','cyan-a3','cyan-a4'];
var tealPalette = ['teal-0','teal-1','teal-2','teal-3','teal-4','teal','teal-6','teal-7','teal-8','teal-9','teal-a1','teal-a2','teal-a3','teal-a4'];
var greenPalette = ['green-0','green-1','green-2','green-3','green-4','green','green-6','green-7','green-8','green-9','green-a1','green-a2','green-a3','green-a4'];
var lightGreenPalette = ['light-green-0','light-green-1','light-green-2','light-green-3','light-green-4','light-green','light-green-6','light-green-7','light-green-8','light-green-9','light-green-a1','light-green-a2','light-green-a3','light-green-a4'];
var limePalette = ['lime-0','lime-1','lime-2','lime-3','lime-4','lime','lime-6','lime-7','lime-8','lime-9','lime-a1','lime-a2','lime-a3','lime-a4'];
var yellowPalette = ['yellow-0','yellow-1','yellow-2','yellow-3','yellow-4','yellow','yellow-6','yellow-7','yellow-8','yellow-9','yellow-a1','yellow-a2','yellow-a3','yellow-a4'];
var amberPalette = ['amber-0','amber-1','amber-2','amber-3','amber-4','amber','amber-6','amber-7','amber-8','amber-9','amber-a1','amber-a2','amber-a3','amber-a4'];
var orangePalette = ['orange-0','orange-1','orange-2','orange-3','orange-4','orange','orange-6','orange-7','orange-8','orange-9','orange-a1','orange-a2','orange-a3','orange-a4'];
var deepOrangePalette = ['deep-orange-0','deep-orange-1','deep-orange-2','deep-orange-3','deep-orange-4','deep-orange','deep-orange-6','deep-orange-7','deep-orange-8','deep-orange-9','deep-orange-a1','deep-orange-a2','deep-orange-a3','deep-orange-a4'];
var brownPalette = ['brown-0','brown-1','brown-2','brown-3','brown-4','brown','brown-6','brown-7','brown-8','brown-9'];
var greyPalette = ['grey-0','grey-1','grey-2','grey-3','grey-4','grey','grey-6','grey-7','grey-8','grey-9'];
var blueGreyPalette = ['blue-grey-0','blue-grey-1','blue-grey-2','blue-grey-3','blue-grey-4','blue-grey','blue-grey-6','blue-grey-7','blue-grey-8','blue-grey-9'];
var blackPalette = ['black'];
var whitePalette = ['white'];
var colorPalettes = ['redPalette','pinkPalette','purplePalette','deepPurplePalette','indigoPalette','bluePalette','lightBluePalette','cyanPalette','tealPalette','greenPalette','lightGreenPalette','limePalette','yellowPalette','amberPalette','orangePalette','deepOrangePalette','brownPalette','greyPalette','blueGreyPalette']; //+'blackPalette','whitePalette'
str = '';
str = "<div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-black p-1 w-100 t-center colored'>black</div></div><div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-white p-1 w-100 t-center colored'>white</div></div><div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-white p-1 w-100 t-center colored'>black</div></div><div class='no-gutter col col-m-2 col-t-4 col-6'><div class='bg-black p-1 w-100 t-center colored'>white</div></div>";
for (var i = 0; i < colorPalettes.length; i++) {
str += "<div class='no-gutter col col-2 bg-" + window[colorPalettes[i]][9] + "'>";
for (var j = 0; j < window[colorPalettes[i]].length; j++) {
str += "<div class='bg-" + window[colorPalettes[i]][j] + " p-1 w-100 t-center colored'> " + window[colorPalettes[i]][j] + " </div>";
}
str += "</div>";
}
for (var i = 0; i < colorPalettes.length; i++) {
str += "<div class='bg-black no-gutter col col-2'>";
for (var j = 0; j < window[colorPalettes[i]].length; j++) {
str += "<div class='text-" + window[colorPalettes[i]][j] + " p-1 w-100 t-center colored'> " + window[colorPalettes[i]][j] + " </div>";
}
str += "</div>";
}
document.getElementById("colorPalettesBlock").innerHTML = str;
</script>
</div>
| ostux/tacss | utilities/colors.html | HTML | mit | 16,433 |
---
layout: post
title: "Clean Code: Chapter 5 - Formatting"
date: 2016-03-13
---
Formatting, while not consequential to how the code actually works, does make a huge difference in how future user of the code will be able to navigate and understand what is going on.
In formatting, particularly, the broken window theory applies. The broken window theory is a social science concept that looks at how a single, small act of neglect can lead to snowballing negative effects. The theory gets its name from the idea that a single neglected broken window in an abandoned building would eventually invite more acts of crime and vandalism.
This applies to programming because a consistently and cleanly formatted application reinforces the importance of setting positive norms for future results. Lazy formatting, on the other hand, will set a precedent for those who will add to and edit the code down the line.
There are several aspects that go into a well formatted application. Vertical and horizontal formatting are a couple of considerations to make when considering how your code and files should be organized.
### Vertical Formatting
>Smaller files are usually easier to understand than large files are.
Vertical formatting points to a file’s overall size with regards to lines of code per file. As a general rule, you don’t want to have files over 500 lines of code, but even smaller files are easier to sort through.
Beyond just lines of code, however, are vertical context guidelines. Code should be organized in a file in a meaningful way, with larger concepts towards the top, and smaller and smaller details as one descends down the file. Functions that call other functions should appear above the functions which they call. Variables that are used throughout the file should remain at the top of the file, and local variables should appear at the top of the function that is using them.
With the code organized, you can make other considerations with regards to spacing.
It is appropriate to use empty lines to separate concepts, such as functions. Within a grouped concept, however, using empty lines can draw out methods, making them more difficult to follow.
### Horizontal Formatting
Horizontal formatting, on the other hand, deals with the smaller context of single lines. The guideline for how long your lines should be should take into consideration a reader and the required movement it would take to read from left to right. You don’t want the reader to have to scroll to read a full line, nor would you want to have to shrink the font to a tiny size to get a single line effect. Typically 100-120 characters per line are appropriate.
> We use horizontal white space to associate things that are strongly related and dissassociate things that are more weakly related.
Spacing can have a positive effect on the readability of the code. Consider the following:
```function area(length,width){
return (length*width)/2
}```
Sure, the code runs and does what it is supposed to, but a user friendly refactor could be as follows:
```function area(length, width) {
return (length * width) / 2
}```
Just adding a couple of spaces saves time in allowing yourself to separate the different actions happening in the code.
As another consideration, it is generally not wise to separate things into a column format, as the eye tends to follow the vertical line of the column, rather than the horizontal line as intended.
Indentation is another important horizontal formatting concept. Consider the file as an outline and indent as such. The larger concepts such as class or module declaration would appear farthest left, with smaller details within functions and loops being indented the most. This helps readers know where concepts begin and end.
Paying attention to vertical and horizontal formatting concepts will go a long way in presenting a clean code base that others will want to work with. Keep in mind a goal that you want people to look at your code and think *”wow, this person really cares”*. | NicoleCarpenter/nicolecarpenter.github.io | _posts/2016-03-13-clean-code-chapter-5-formatting.md | Markdown | mit | 4,058 |
# testtesttest-yo
[![NPM version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Dependency Status][daviddm-image]][daviddm-url]
[![Code Coverage][coverage-image]][coverage-url]
[![Code Climate][climate-image]][climate-url]
[![License][license-image]][license-url]
[![Code Style][code-style-image]][code-style-url]
## Table of Contents
1. [Features](#features)
1. [Requirements](#requirements)
1. [Getting Started](#getting-started)
1. [Application Structure](#application-structure)
1. [Development](#development)
1. [Routing](#routing)
1. [Testing](#testing)
1. [Configuration](#configuration)
1. [Production](#production)
1. [Deployment](#deployment)
## Requirements
* node `^5.0.0` (`6.11.0` suggested)
* yarn `^0.23.0` or npm `^3.0.0`
## Getting Started
1. Install dependencies: `yarn` or `npm install`
2. Start Development server: `yarn start` or `npm start`
While developing, you will probably rely mostly on `npm start`; however, there are additional scripts at your disposal:
|`npm run <script>` |Description|
|-------------------|-----------|
|`start` |Serves your app at `localhost:3000` and displays [Webpack Dashboard](https://github.com/FormidableLabs/webpack-dashboard)|
|`start:simple` |Serves your app at `localhost:3000` without [Webpack Dashboard](https://github.com/FormidableLabs/webpack-dashboard)|
|`build` |Builds the application to ./dist|
|`test` |Runs unit tests with Karma. See [testing](#testing)|
|`test:watch` |Runs `test` in watch mode to re-run tests when changed|
|`lint` |[Lints](http://stackoverflow.com/questions/8503559/what-is-linting) the project for potential errors|
|`lint:fix` |Lints the project and [fixes all correctable errors](http://eslint.org/docs/user-guide/command-line-interface.html#fix)|
[Husky](https://github.com/typicode/husky) is used to enable `prepush` hook capability. The `prepush` script currently runs `eslint`, which will keep you from pushing if there is any lint within your code. If you would like to disable this, remove the `prepush` script from the `package.json`.
## Application Structure
The application structure presented in this boilerplate is **fractal**, where functionality is grouped primarily by feature rather than file type. Please note, however, that this structure is only meant to serve as a guide, it is by no means prescriptive. That said, it aims to represent generally accepted guidelines and patterns for building scalable applications. If you wish to read more about this pattern, please check out this [awesome writeup](https://github.com/davezuko/react-redux-starter-kit/wiki/Fractal-Project-Structure) by [Justin Greenberg](https://github.com/justingreenberg).
```
.
├── build # All build-related configuration
│ └── create-config # Script for building config.js in ci environments
│ └── karma.config.js # Test configuration for Karma
│ └── webpack.config.js # Environment-specific configuration files for webpack
├── server # Express application that provides webpack middleware
│ └── main.js # Server application entry point
├── src # Application source code
│ ├── index.html # Main HTML page container for app
│ ├── main.js # Application bootstrap and rendering
│ ├── normalize.js # Browser normalization and polyfills
│ ├── components # Global Reusable Presentational Components
│ ├── containers # Global Reusable Container Components
│ ├── layouts # Components that dictate major page structure
│ │ └── CoreLayout # Global application layout in which to render routes
│ ├── routes # Main route definitions and async split points
│ │ ├── index.js # Bootstrap main application routes with store
│ │ └── Home # Fractal route
│ │ ├── index.js # Route definitions and async split points
│ │ ├── assets # Assets required to render components
│ │ ├── components # Presentational React Components
│ │ ├── container # Connect components to actions and store
│ │ ├── modules # Collections of reducers/constants/actions
│ │ └── routes ** # Fractal sub-routes (** optional)
│ ├── static # Static assets
│ ├── store # Redux-specific pieces
│ │ ├── createStore.js # Create and instrument redux store
│ │ └── reducers.js # Reducer registry and injection
│ └── styles # Application-wide styles (generally settings)
├── project.config.js # Project configuration settings (includes ci settings)
└── tests # Unit tests
```
### Routing
We use `react-router` [route definitions](https://github.com/ReactTraining/react-router/blob/v3/docs/API.md#plainroute) (`<route>/index.js`) to define units of logic within our application. See the [application structure](#application-structure) section for more information.
## Testing
To add a unit test, create a `.spec.js` file anywhere inside of `./tests`. Karma and webpack will automatically find these files, and Mocha and Chai will be available within your test without the need to import them.
## Production
Build code before deployment by running `npm run build`. There are multiple options below for types of deployment, if you are unsure, checkout the Firebase section.
### Deployment
1. Login to [Firebase](firebase.google.com) (or Signup if you don't have an account) and create a new project
2. Install cli: `npm i -g firebase-tools`
#### CI Deploy (recommended)
**Note**: Config for this is located within `travis.yml`
`firebase-ci` has been added to simplify the CI deployment process. All that is required is providing authentication with Firebase:
1. Login: `firebase login:ci` to generate an authentication token (will be used to give Travis-CI rights to deploy on your behalf)
1. Set `FIREBASE_TOKEN` environment variable within Travis-CI environment
1. Run a build on Travis-CI
If you would like to deploy to different Firebase instances for different branches (i.e. `prod`), change `ci` settings within `.firebaserc`.
For more options on CI settings checkout the [firebase-ci docs](https://github.com/prescottprue/firebase-ci)
#### Manual deploy
1. Run `firebase:login`
1. Initialize project with `firebase init` then answer:
* What file should be used for Database Rules? -> `database.rules.json`
* What do you want to use as your public directory? -> `build`
* Configure as a single-page app (rewrite all urls to /index.html)? -> `Yes`
* What Firebase project do you want to associate as default? -> **your Firebase project name**
1. Build Project: `npm run build`
1. Confirm Firebase config by running locally: `firebase serve`
1. Deploy to firebase: `firebase deploy`
**NOTE:** You can use `firebase serve` to test how your application will work when deployed to Firebase, but make sure you run `npm run build` first.
[npm-image]: https://img.shields.io/npm/v/testtesttest-yo.svg?style=flat-square
[npm-url]: https://npmjs.org/package/testtesttest-yo
[travis-image]: https://img.shields.io/travis/[email protected]/testtesttest-yo/master.svg?style=flat-square
[travis-url]: https://travis-ci.org/[email protected]/testtesttest-yo
[daviddm-image]: https://img.shields.io/david/[email protected]/testtesttest-yo.svg?style=flat-square
[daviddm-url]: https://david-dm.org/[email protected]/testtesttest-yo
[climate-image]: https://img.shields.io/codeclimate/github/[email protected]/testtesttest-yo.svg?style=flat-square
[climate-url]: https://codeclimate.com/github/[email protected]/testtesttest-yo
[coverage-image]: https://img.shields.io/codeclimate/coverage/github/[email protected]/testtesttest-yo.svg?style=flat-square
[coverage-url]: https://codeclimate.com/github/[email protected]/testtesttest-yo
[license-image]: https://img.shields.io/npm/l/testtesttest-yo.svg?style=flat-square
[license-url]: https://github.com/[email protected]/testtesttest-yo/blob/master/LICENSE
[code-style-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square
[code-style-url]: http://standardjs.com/
| taforyou/testtesttest-yo | README.md | Markdown | mit | 8,556 |
package com.board.gd.domain.stock;
import lombok.Data;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by gd.godong9 on 2017. 5. 19.
*/
@Data
public class StockResult {
private Long id;
private String name;
private String code;
public static StockResult getStockResult(Stock stock) {
StockResult stockResult = new StockResult();
stockResult.setId(stock.getId());
stockResult.setName(stock.getName());
stockResult.setCode(stock.getCode());
return stockResult;
}
public static List<StockResult> getStockResultList(List<Stock> stockList) {
return stockList.stream()
.map(stock -> getStockResult(stock))
.collect(Collectors.toList());
}
}
| godong9/spring-board | board/src/main/java/com/board/gd/domain/stock/StockResult.java | Java | mit | 777 |
<?php
/**
* General purpose and commonly used PHP interface definitions
*
* @author Михаил Красильников <[email protected]>
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Mekras\Interfaces\Http\Message;
use Psr\Http\Message\RequestInterface;
/**
* HTTP request factory
*
* Object can create empty instances of {@link \Psr\Http\Message\RequestInterface}.
* This can be used to abstract from concrete PSR-7 implementation.
*
* @deprecated use https://packagist.org/packages/php-http/httplug
*
* @since 3.4 deprecated
* @since 3.02
*/
interface RequestFactory
{
/**
* Create empty HTTP request
*
* @return RequestInterface
*
* @since 3.02
*/
public function createEmptyRequest();
}
| mekras/interfaces | lib/Http/Message/RequestFactory.php | PHP | mit | 775 |
<!--
Unsafe sample
input : get the UserData field of $_SESSION
Uses a number_float_filter via filter_var function
File : unsafe, use of untrusted data in CSS
-->
<!--Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.-->
<!DOCTYPE html>
<html>
<head>
<style>
<?php
$tainted = $_SESSION['UserData'];
$sanitized = filter_var($tainted, FILTER_SANITIZE_NUMBER_FLOAT);
if (filter_var($sanitized, FILTER_VALIDATE_FLOAT))
$tainted = $sanitized ;
else
$tainted = "" ;
//flaw
echo $tainted ;
?>
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html> | stivalet/PHP-Vulnerability-test-suite | XSS/CWE_79/unsafe/CWE_79__SESSION__func_FILTER-CLEANING-number_float_filter__Unsafe_use_untrusted_data-style.php | PHP | mit | 1,407 |
var today = new Date();
console.log(today); | johnvoon/launch_school | 210/lesson5/date_ex1.js | JavaScript | mit | 43 |
var RocketBoots = {
isInitialized : false,
readyFunctions : [],
components : {},
loadedScripts: [],
version: {full: "0.7.0", major: 0, minor: 7, patch: 0, codeName: "sun-master"},
_autoLoadRequirements: true,
_initTimer : null,
_MAX_ATTEMPTS : 300,
_BOOTING_ELEMENT_ID : "booting-up-rocket-boots",
_: null, // Lodash
$: null, // jQuery
//==== Classes
Component : function(c){
this.fileName = c;
this.name = null;
this.isLoaded = false;
this.isInstalled = false;
},
//==== General Functions
log : console.log,
loadScript : function(url, callback){
//console.log("Loading script", url);
// http://stackoverflow.com/a/7719185/1766230
var o = this;
var s = document.createElement('script');
var r = false;
var t;
s.type = 'text/javascript';
s.src = "scripts/" + url + ".js";
s.className = "rocketboots-script";
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState ); //uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
o.loadedScripts.push(url);
if (typeof callback == "function") callback();
}
};
t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s, t);
return this;
},
//==== Component Functions
hasComponent: function (componentClass) {
if (typeof RocketBoots[componentClass] == "function") {
return true;
} else {
return false;
}
},
installComponent : function (options, callback, attempt) {
// options = { fileName, classNames, requirements, description, credits }
var o = this;
var mainClassName = (typeof options.classNames === 'object' && options.classNames.length > 0) ? options.classNames[0] : (options.classNames || options.className);
var componentClass = options[mainClassName];
var requirements = options.requirements;
var fileName = options.fileName;
var callbacks = [];
var i;
// Setup array of callbacks
if (typeof callback === 'function') { callbacks.push(callback); }
if (typeof options.callback === 'function') { callbacks.push(options.callback); }
if (typeof options.callbacks === 'object') { callbacks.concat(options.callbacks); }
// Check for possible errors
if (typeof mainClassName !== 'string') {
console.error("Error installing component: mainClassName is not a string", mainClassName, options);
console.log("options", options);
return;
} else if (typeof componentClass !== 'function') {
console.error("Error installing component: class name", mainClassName, "not found on options:", options);
console.log("options", options);
return;
}
//console.log("Installing", fileName, " ...Are required components", requirements, " loaded?", o.areComponentsLoaded(requirements));
if (!o.areComponentsLoaded(requirements)) {
var tryAgainDelay, compTimer;
if (typeof attempt === "undefined") {
attempt = 1;
} else if (attempt > o._MAX_ATTEMPTS) {
console.error("Could not initialize RocketBoots: too many attempts");
return false;
} else {
attempt++;
}
if (o._autoLoadRequirements) {
console.log(fileName, "requires component(s)", requirements, " which aren't loaded. Autoloading...");
o.loadComponents(requirements);
tryAgainDelay = 100 * attempt;
} else {
console.warn(fileName, "requires component(s)", requirements, " which aren't loaded.");
tryAgainDelay = 5000;
}
compTimer = window.setTimeout(function(){
o.installComponent(options, callback, attempt);
}, tryAgainDelay);
} else {
if (typeof o.components[fileName] == "undefined") {
o.components[fileName] = new o.Component(fileName);
}
/*
for (i = 0; i < callbacks.length; i++) {
if (typeof callbacks[i] === "function") {
callbacks[i]();
}
}
*/
o.components[fileName].name = mainClassName;
o.components[fileName].isInstalled = true;
o.components[fileName].callbacks = callbacks;
// TODO: Add description and credits
//o.components[fileName].description = "";
//o.components[fileName].credits = "";
o[mainClassName] = componentClass;
}
return this;
},
getComponentByName: function (componentName) {
var o = this;
for (var cKey in o.components) {
if (o.components[cKey].name == componentName) {
return o.components[cKey];
}
};
return;
},
areComponentsLoaded: function (componentNameArr) {
var o = this, areLoaded = true;
if (typeof componentNameArr !== 'object') {
return areLoaded;
}
for (var i = 0; i < componentNameArr.length; i++) {
if (!o.isComponentInstalled(componentNameArr[i])) { areLoaded = false; }
};
return areLoaded;
},
isComponentInstalled: function (componentName) {
var comp = this.getComponentByName(componentName);
return (comp && comp.isInstalled);
},
loadComponents : function(arr, path){
var o = this;
var componentName;
path = (typeof path === 'undefined') ? "rocketboots/" : path;
for (var i = 0, al = arr.length; i < al; i++){
componentName = arr[i];
if (typeof o.components[componentName] == "undefined") {
o.components[componentName] = new o.Component(componentName);
o.loadScript(path + arr[i], function(){
o.components[componentName].isLoaded = true;
});
} else {
//console.warn("Trying to load", componentName, "component that already exists.");
}
}
return this;
},
loadCustomComponents : function (arr, path) {
path = (typeof path === 'undefined') ? "" : path;
return this.loadComponents(arr, path);
},
areAllComponentsLoaded : function(){
var o = this;
var componentCount = 0,
componentsInstalledCount = 0;
for (var c in o.components) {
// if (o.components.hasOwnProperty(c)) { do stuff }
componentCount++;
if (o.components[c].isInstalled) componentsInstalledCount++;
}
console.log("RB Components Installed: " + componentsInstalledCount + "/" + componentCount);
return (componentsInstalledCount >= componentCount);
},
//==== Ready and Init Functions
ready : function(callback){
if (typeof callback == "function") {
if (this.isInitialized) {
callback(this);
} else {
this.readyFunctions.push(callback);
}
} else {
console.error("Ready argument (callback) not a function");
}
return this;
},
runReadyFunctions : function(){
var o = this;
// Loop over readyFunctions and run each one
var f, fn;
for (var i = 0; o.readyFunctions.length > 0; i++){
f = o.readyFunctions.splice(i,1);
fn = f[0];
fn(o);
}
return this;
},
init : function(attempt){
var o = this;
// TODO: allow dependecies to be injected rather than forcing them to be on the window scope
var isJQueryUndefined = (typeof $ === "undefined");
var isLodashUndefined = (typeof _ === "undefined");
var areRequiredScriptsMissing = isJQueryUndefined || isLodashUndefined;
if (typeof attempt === "undefined") {
attempt = 1;
} else if (attempt > o._MAX_ATTEMPTS) {
console.error("Could not initialize RocketBoots: too many attempts");
return false;
} else {
attempt++;
}
//console.log("RB Init", attempt, (areRequiredScriptsMissing ? "Waiting on required objects from external scripts" : ""));
if (!isJQueryUndefined) {
o.$ = $;
o.$('#' + o._BOOTING_ELEMENT_ID).show();
}
if (!isLodashUndefined) {
o._ = _;
o.each = o.forEach = _.each;
}
function tryAgain () {
// Clear previous to stop multiple inits from happening
window.clearTimeout(o._initTimer);
o._initTimer = window.setTimeout(function(){
o.init(attempt);
}, (attempt * 10));
}
// On first time through, do some things
if (attempt === 1) {
// Create "rb" alias
if (typeof window.rb !== "undefined") {
o._rb = window.rb;
}
window.rb = o;
// Aliases
o.window = window;
o.document = window.document;
// Load default components
// TODO: make this configurable
this.loadComponents(["Game"]);
// Load required scripts
if (isJQueryUndefined) {
o.loadScript("libs/jquery-2.2.4.min", function(){
//o.init(1);
});
}
if (isLodashUndefined) {
o.loadScript("libs/lodash.min", function(){ });
}
}
if (o.areAllComponentsLoaded() && !areRequiredScriptsMissing) {
console.log("RB Init - All scripts and components are loaded.", o.loadedScripts, "\nRunning component callbacks...");
// TODO: These don't necessarily run in the correct order for requirements
o.each(o.components, function(component){
o.each(component.callbacks, function(callback){
console.log("Callback for", component.name);
callback(); // TODO: Make this run in the right context?
});
});
console.log("RB Init - Running Ready functions.\n");
o.$('#' + o._BOOTING_ELEMENT_ID).hide();
o.runReadyFunctions();
o.isInitialized = true;
return true;
}
tryAgain();
return false;
}
};
RocketBoots.init();
| Lukenickerson/rocketboots | scripts/rocketboots/core.js | JavaScript | mit | 8,886 |
<?php
namespace ErenMustafaOzdal\LaravelModulesBase;
use Illuminate\Database\Eloquent\Model;
class Neighborhood extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'neighborhoods';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['neighborhood'];
public $timestamps = false;
/*
|--------------------------------------------------------------------------
| Model Relations
|--------------------------------------------------------------------------
*/
/**
* Get the postal code of the district.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function postalCode()
{
return $this->hasOne('App\PostalCode');
}
/*
|--------------------------------------------------------------------------
| Model Set and Get Attributes
|--------------------------------------------------------------------------
*/
/**
* get the neighborhood uc first
*
* @return string
*/
public function getNeighborhoodUcFirstAttribute()
{
return ucfirst_tr($this->neighborhood);
}
}
| erenmustafaozdal/laravel-modules-base | src/Neighborhood.php | PHP | mit | 1,262 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
// Key used by getwork/getblocktemplate miners.
// Allocated in StartRPCThreads, free'd in StopRPCThreads
CReserveKey* pMiningKey = NULL;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 5745 : 13000;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 12000000)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop Netbits server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "Netbits server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe
// ------------------------ ----------------------- ---------- ----------
{ "help", &help, true, true },
{ "stop", &stop, true, true },
{ "getblockcount", &getblockcount, true, false },
{ "getconnectioncount", &getconnectioncount, true, false },
{ "getpeerinfo", &getpeerinfo, true, false },
{ "addnode", &addnode, true, true },
{ "getaddednodeinfo", &getaddednodeinfo, true, true },
{ "getdifficulty", &getdifficulty, true, false },
{ "getgenerate", &getgenerate, true, false },
{ "setgenerate", &setgenerate, true, false },
{ "gethashespersec", &gethashespersec, true, false },
{ "getinfo", &getinfo, true, false },
{ "getmininginfo", &getmininginfo, true, false },
{ "getnewaddress", &getnewaddress, true, false },
{ "getaccountaddress", &getaccountaddress, true, false },
{ "setaccount", &setaccount, true, false },
{ "getaccount", &getaccount, false, false },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false },
{ "sendtoaddress", &sendtoaddress, false, false },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false },
{ "backupwallet", &backupwallet, true, false },
{ "keypoolrefill", &keypoolrefill, true, false },
{ "walletpassphrase", &walletpassphrase, true, false },
{ "walletpassphrasechange", &walletpassphrasechange, false, false },
{ "walletlock", &walletlock, true, false },
{ "encryptwallet", &encryptwallet, false, false },
{ "validateaddress", &validateaddress, true, false },
{ "getbalance", &getbalance, false, false },
{ "move", &movecmd, false, false },
{ "sendfrom", &sendfrom, false, false },
{ "sendmany", &sendmany, false, false },
{ "addmultisigaddress", &addmultisigaddress, false, false },
{ "createmultisig", &createmultisig, true, true },
{ "getrawmempool", &getrawmempool, true, false },
{ "getblock", &getblock, false, false },
{ "getblockhash", &getblockhash, false, false },
{ "gettransaction", &gettransaction, false, false },
{ "listtransactions", &listtransactions, false, false },
{ "listaddressgroupings", &listaddressgroupings, false, false },
{ "signmessage", &signmessage, false, false },
{ "verifymessage", &verifymessage, false, false },
{ "getwork", &getwork, true, false },
{ "listaccounts", &listaccounts, false, false },
{ "settxfee", &settxfee, false, false },
{ "getblocktemplate", &getblocktemplate, true, false },
{ "submitblock", &submitblock, false, false },
{ "listsinceblock", &listsinceblock, false, false },
{ "dumpprivkey", &dumpprivkey, true, false },
{ "importprivkey", &importprivkey, false, false },
{ "listunspent", &listunspent, false, false },
{ "getrawtransaction", &getrawtransaction, false, false },
{ "createrawtransaction", &createrawtransaction, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false },
{ "signrawtransaction", &signrawtransaction, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false },
{ "gettxout", &gettxout, true, false },
{ "lockunspent", &lockunspent, false, false },
{ "listlockunspent", &listlockunspent, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: netbits-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: netbits-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: netbits-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use netbitsd";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=netbitsrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Netbits Alert\" [email protected]\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
delete pMiningKey; pMiningKey = NULL;
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| net-bits/Netbits | src/bitcoinrpc.cpp | C++ | mit | 46,782 |
#!/usr/bin/env python3
# Copyright (c) 2015-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Utilities for manipulating blocks and transactions."""
import struct
import time
import unittest
from .address import (
key_to_p2sh_p2wpkh,
key_to_p2wpkh,
script_to_p2sh_p2wsh,
script_to_p2wsh,
)
from .messages import (
CBlock,
COIN,
COutPoint,
CTransaction,
CTxIn,
CTxInWitness,
CTxOut,
hash256,
ser_uint256,
tx_from_hex,
uint256_from_str,
)
from .script import (
CScript,
CScriptNum,
CScriptOp,
OP_1,
OP_CHECKMULTISIG,
OP_CHECKSIG,
OP_RETURN,
OP_TRUE,
)
from .script_util import (
key_to_p2wpkh_script,
script_to_p2wsh_script,
)
from .util import assert_equal
WITNESS_SCALE_FACTOR = 4
MAX_BLOCK_SIGOPS = 20000
MAX_BLOCK_SIGOPS_WEIGHT = MAX_BLOCK_SIGOPS * WITNESS_SCALE_FACTOR
# Genesis block time (regtest)
TIME_GENESIS_BLOCK = 1296688602
# Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
COINBASE_MATURITY = 100
# Soft-fork activation heights
DERSIG_HEIGHT = 102 # BIP 66
CLTV_HEIGHT = 111 # BIP 65
CSV_ACTIVATION_HEIGHT = 432
# From BIP141
WITNESS_COMMITMENT_HEADER = b"\xaa\x21\xa9\xed"
NORMAL_GBT_REQUEST_PARAMS = {"rules": ["segwit"]}
VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4
def create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl=None, txlist=None):
"""Create a block (with regtest difficulty)."""
block = CBlock()
if tmpl is None:
tmpl = {}
block.nVersion = version or tmpl.get('version') or VERSIONBITS_LAST_OLD_BLOCK_VERSION
block.nTime = ntime or tmpl.get('curtime') or int(time.time() + 600)
block.hashPrevBlock = hashprev or int(tmpl['previousblockhash'], 0x10)
if tmpl and not tmpl.get('bits') is None:
block.nBits = struct.unpack('>I', bytes.fromhex(tmpl['bits']))[0]
else:
block.nBits = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams
if coinbase is None:
coinbase = create_coinbase(height=tmpl['height'])
block.vtx.append(coinbase)
if txlist:
for tx in txlist:
if not hasattr(tx, 'calc_sha256'):
tx = tx_from_hex(tx)
block.vtx.append(tx)
block.hashMerkleRoot = block.calc_merkle_root()
block.calc_sha256()
return block
def get_witness_script(witness_root, witness_nonce):
witness_commitment = uint256_from_str(hash256(ser_uint256(witness_root) + ser_uint256(witness_nonce)))
output_data = WITNESS_COMMITMENT_HEADER + ser_uint256(witness_commitment)
return CScript([OP_RETURN, output_data])
def add_witness_commitment(block, nonce=0):
"""Add a witness commitment to the block's coinbase transaction.
According to BIP141, blocks with witness rules active must commit to the
hash of all in-block transactions including witness."""
# First calculate the merkle root of the block's
# transactions, with witnesses.
witness_nonce = nonce
witness_root = block.calc_witness_merkle_root()
# witness_nonce should go to coinbase witness.
block.vtx[0].wit.vtxinwit = [CTxInWitness()]
block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ser_uint256(witness_nonce)]
# witness commitment is the last OP_RETURN output in coinbase
block.vtx[0].vout.append(CTxOut(0, get_witness_script(witness_root, witness_nonce)))
block.vtx[0].rehash()
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
def script_BIP34_coinbase_height(height):
if height <= 16:
res = CScriptOp.encode_op_n(height)
# Append dummy to increase scriptSig size above 2 (see bad-cb-length consensus rule)
return CScript([res, OP_1])
return CScript([CScriptNum(height)])
def create_coinbase(height, pubkey=None, extra_output_script=None, fees=0, nValue=50):
"""Create a coinbase transaction.
If pubkey is passed in, the coinbase output will be a P2PK output;
otherwise an anyone-can-spend output.
If extra_output_script is given, make a 0-value output to that
script. This is useful to pad block weight/sigops as needed. """
coinbase = CTransaction()
coinbase.vin.append(CTxIn(COutPoint(0, 0xffffffff), script_BIP34_coinbase_height(height), 0xffffffff))
coinbaseoutput = CTxOut()
coinbaseoutput.nValue = nValue * COIN
if nValue == 50:
halvings = int(height / 150) # regtest
coinbaseoutput.nValue >>= halvings
coinbaseoutput.nValue += fees
if pubkey is not None:
coinbaseoutput.scriptPubKey = CScript([pubkey, OP_CHECKSIG])
else:
coinbaseoutput.scriptPubKey = CScript([OP_TRUE])
coinbase.vout = [coinbaseoutput]
if extra_output_script is not None:
coinbaseoutput2 = CTxOut()
coinbaseoutput2.nValue = 0
coinbaseoutput2.scriptPubKey = extra_output_script
coinbase.vout.append(coinbaseoutput2)
coinbase.calc_sha256()
return coinbase
def create_tx_with_script(prevtx, n, script_sig=b"", *, amount, script_pub_key=CScript()):
"""Return one-input, one-output transaction object
spending the prevtx's n-th output with the given amount.
Can optionally pass scriptPubKey and scriptSig, default is anyone-can-spend output.
"""
tx = CTransaction()
assert n < len(prevtx.vout)
tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), script_sig, 0xffffffff))
tx.vout.append(CTxOut(amount, script_pub_key))
tx.calc_sha256()
return tx
def create_transaction(node, txid, to_address, *, amount):
""" Return signed transaction spending the first output of the
input txid. Note that the node must have a wallet that can
sign for the output that is being spent.
"""
raw_tx = create_raw_transaction(node, txid, to_address, amount=amount)
tx = tx_from_hex(raw_tx)
return tx
def create_raw_transaction(node, txid, to_address, *, amount):
""" Return raw signed transaction spending the first output of the
input txid. Note that the node must have a wallet that can sign
for the output that is being spent.
"""
psbt = node.createpsbt(inputs=[{"txid": txid, "vout": 0}], outputs={to_address: amount})
for _ in range(2):
for w in node.listwallets():
wrpc = node.get_wallet_rpc(w)
signed_psbt = wrpc.walletprocesspsbt(psbt)
psbt = signed_psbt['psbt']
final_psbt = node.finalizepsbt(psbt)
assert_equal(final_psbt["complete"], True)
return final_psbt['hex']
def get_legacy_sigopcount_block(block, accurate=True):
count = 0
for tx in block.vtx:
count += get_legacy_sigopcount_tx(tx, accurate)
return count
def get_legacy_sigopcount_tx(tx, accurate=True):
count = 0
for i in tx.vout:
count += i.scriptPubKey.GetSigOpCount(accurate)
for j in tx.vin:
# scriptSig might be of type bytes, so convert to CScript for the moment
count += CScript(j.scriptSig).GetSigOpCount(accurate)
return count
def witness_script(use_p2wsh, pubkey):
"""Create a scriptPubKey for a pay-to-witness TxOut.
This is either a P2WPKH output for the given pubkey, or a P2WSH output of a
1-of-1 multisig for the given pubkey. Returns the hex encoding of the
scriptPubKey."""
if not use_p2wsh:
# P2WPKH instead
pkscript = key_to_p2wpkh_script(pubkey)
else:
# 1-of-1 multisig
witness_script = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG])
pkscript = script_to_p2wsh_script(witness_script)
return pkscript.hex()
def create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount):
"""Return a transaction (in hex) that spends the given utxo to a segwit output.
Optionally wrap the segwit output using P2SH."""
if use_p2wsh:
program = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG])
addr = script_to_p2sh_p2wsh(program) if encode_p2sh else script_to_p2wsh(program)
else:
addr = key_to_p2sh_p2wpkh(pubkey) if encode_p2sh else key_to_p2wpkh(pubkey)
if not encode_p2sh:
assert_equal(node.getaddressinfo(addr)['scriptPubKey'], witness_script(use_p2wsh, pubkey))
return node.createrawtransaction([utxo], {addr: amount})
def send_to_witness(use_p2wsh, node, utxo, pubkey, encode_p2sh, amount, sign=True, insert_redeem_script=""):
"""Create a transaction spending a given utxo to a segwit output.
The output corresponds to the given pubkey: use_p2wsh determines whether to
use P2WPKH or P2WSH; encode_p2sh determines whether to wrap in P2SH.
sign=True will have the given node sign the transaction.
insert_redeem_script will be added to the scriptSig, if given."""
tx_to_witness = create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount)
if (sign):
signed = node.signrawtransactionwithwallet(tx_to_witness)
assert "errors" not in signed or len(["errors"]) == 0
return node.sendrawtransaction(signed["hex"])
else:
if (insert_redeem_script):
tx = tx_from_hex(tx_to_witness)
tx.vin[0].scriptSig += CScript([bytes.fromhex(insert_redeem_script)])
tx_to_witness = tx.serialize().hex()
return node.sendrawtransaction(tx_to_witness)
class TestFrameworkBlockTools(unittest.TestCase):
def test_create_coinbase(self):
height = 20
coinbase_tx = create_coinbase(height=height)
assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), height)
| yenliangl/bitcoin | test/functional/test_framework/blocktools.py | Python | mit | 9,688 |
#include "StdAfx.h"
#include "Distance Joint Description.h"
#include "Spring Description.h"
#include "Distance Joint.h"
#include <NxDistanceJointDesc.h>
using namespace StillDesign::PhysX;
DistanceJointDescription::DistanceJointDescription() : JointDescription( new NxDistanceJointDesc() )
{
}
DistanceJointDescription::DistanceJointDescription( NxDistanceJointDesc* desc ) : JointDescription( desc )
{
}
float DistanceJointDescription::MinimumDistance::get()
{
return this->UnmanagedPointer->minDistance;
}
void DistanceJointDescription::MinimumDistance::set( float value )
{
this->UnmanagedPointer->minDistance = value;
}
float DistanceJointDescription::MaximumDistance::get()
{
return this->UnmanagedPointer->maxDistance;
}
void DistanceJointDescription::MaximumDistance::set( float value )
{
this->UnmanagedPointer->maxDistance = value;
}
SpringDescription DistanceJointDescription::Spring::get()
{
return (SpringDescription)this->UnmanagedPointer->spring;
}
void DistanceJointDescription::Spring::set( SpringDescription value )
{
this->UnmanagedPointer->spring = (NxSpringDesc)value;
}
DistanceJointFlag DistanceJointDescription::Flags::get()
{
return (DistanceJointFlag)this->UnmanagedPointer->flags;
}
void DistanceJointDescription::Flags::set( DistanceJointFlag value )
{
this->UnmanagedPointer->flags = (NxDistanceJointFlag)value;
}
NxDistanceJointDesc* DistanceJointDescription::UnmanagedPointer::get()
{
return (NxDistanceJointDesc*)JointDescription::UnmanagedPointer;
} | danteinforno/PhysX.Net | PhysX.Net/PhysX.Net/Source/Distance Joint Description.cpp | C++ | mit | 1,564 |
using UnityEngine;
using UnityEditor;
using System.Collections;
using UForms.Attributes;
namespace UForms.Controls.Fields
{
/// <summary>
///
/// </summary>
[ExposeControl( "Object Field", "Fields" )]
public class ObjectField : AbstractField< Object >
{
/// <summary>
///
/// </summary>
protected override Vector2 DefaultSize
{
get { return new Vector2( 200.0f, 16.0f ); }
}
/// <summary>
///
/// </summary>
protected override bool UseBackingFieldChangeDetection
{
get { return true; }
}
/// <summary>
///
/// </summary>
public System.Type Type { get; set; }
/// <summary>
///
/// </summary>
public bool AllowSceneObjects { get; set; }
public ObjectField() : base ()
{
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="allowSceneObjects"></param>
/// <param name="value"></param>
/// <param name="label"></param>
public ObjectField( System.Type type, bool allowSceneObjects = false, Object value = null, string label = "" ) : base( value, label )
{
Type = type;
AllowSceneObjects = allowSceneObjects;
}
/// <summary>
///
/// </summary>
/// <param name="position"></param>
/// <param name="size"></param>
/// <param name="type"></param>
/// <param name="allowSceneObjects"></param>
/// <param name="value"></param>
/// <param name="label"></param>
public ObjectField( Vector2 position, Vector2 size, System.Type type, bool allowSceneObjects = false, Object value = null, string label = "" ) : base( position, size, value, label )
{
Type = type;
AllowSceneObjects = allowSceneObjects;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected override Object DrawAndUpdateValue()
{
return EditorGUI.ObjectField( ScreenRect, Label, m_cachedValue, Type, AllowSceneObjects );
}
/// <summary>
///
/// </summary>
/// <param name="oldval"></param>
/// <param name="newval"></param>
/// <returns></returns>
protected override bool TestValueEquality( Object oldval, Object newval )
{
if ( oldval == null || newval == null )
{
if ( oldval == null && newval == null )
{
return true;
}
return false;
}
return oldval.Equals( newval );
}
}
} | kilguril/UForms | Assets/UForms/Runtime/Editor/Controls/Fields/ObjectField.cs | C# | mit | 2,890 |
using Microsoft.AspNetCore.Http;
using System.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Primitives;
using System.Globalization;
namespace TCPServer.ServerImplemetation
{
class TCPRequest : HttpRequest
{
private TCPRequest()
{
}
public static async Task<TCPRequest> Parse(TCPStream input, bool includeHeaders)
{
var r = new TCPRequest();
await r.ParseCore(input, includeHeaders).ConfigureAwait(false);
return r;
}
private async Task ParseCore(TCPStream stream, bool includeHeaders)
{
Method = await stream.ReadStringAync().ConfigureAwait(false);
var requestUri = await stream.ReadStringAync().ConfigureAwait(false);
var uri = new Uri(requestUri);
Scheme = uri.Scheme;
IsHttps = false;
Host = new HostString(uri.Host, uri.Port);
PathBase = new PathString(uri.AbsolutePath);
Path = new PathString(uri.AbsolutePath);
QueryString = new QueryString(uri.Query);
Query = new QueryCollection(Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query));
Protocol = "http";
if(includeHeaders)
{
var headers = new List<Tuple<string, string>>();
var headersCount = await stream.ReadVarIntAsync().ConfigureAwait(false);
for(int i = 0; i < (int)headersCount; i++)
{
var key = await stream.ReadStringAync().ConfigureAwait(false);
var value = await stream.ReadStringAync().ConfigureAwait(false);
headers.Add(Tuple.Create(key, value));
}
foreach(var h in headers.GroupBy(g => g.Item1, g => g.Item2))
{
Headers.Add(h.Key, new StringValues(h.ToArray()));
}
}
var hasContent = (await stream.ReadVarIntAsync().ConfigureAwait(false)) == 1;
if(hasContent)
{
var buffer = await stream.ReadBytesAync(TCPStream.ReadType.ManagedPool).ConfigureAwait(false);
Body = new MemoryStream(buffer.Array);
Body.SetLength(buffer.Count);
ContentLength = buffer.Count;
}
}
HttpContext _HttpContext;
public void SetHttpContext(HttpContext context)
{
if(context == null)
throw new ArgumentNullException(nameof(context));
_HttpContext = context;
}
public override HttpContext HttpContext => _HttpContext;
public override string Method
{
get;
set;
}
public override string Scheme
{
get;
set;
}
public override bool IsHttps
{
get;
set;
}
public override HostString Host
{
get;
set;
}
public override PathString PathBase
{
get;
set;
}
public override PathString Path
{
get;
set;
}
public override QueryString QueryString
{
get;
set;
}
public override IQueryCollection Query
{
get;
set;
}
public override string Protocol
{
get;
set;
}
IHeaderDictionary _Headers = new HeaderDictionary();
public override IHeaderDictionary Headers => _Headers;
public override IRequestCookieCollection Cookies
{
get;
set;
} = new RequestCookieCollection();
public override long? ContentLength
{
get
{
StringValues value;
if(!Headers.TryGetValue("Content-Length", out value))
return null;
return long.Parse(value.FirstOrDefault(), CultureInfo.InvariantCulture);
}
set
{
Headers.Remove("Content-Length");
if(value != null)
Headers.Add("Content-Length", value.Value.ToString(CultureInfo.InvariantCulture));
}
}
public override string ContentType
{
get
{
StringValues value;
if(!Headers.TryGetValue("Content-Type", out value))
return null;
return value.FirstOrDefault();
}
set
{
Headers.Remove("Content-Type");
if(value != null)
Headers.Add("Content-Type", new StringValues(value));
}
}
public override Stream Body
{
get;
set;
}
public override bool HasFormContentType => false;
public override IFormCollection Form
{
get;
set;
}
FormCollection _ReadFormAsync = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>());
public override Task<IFormCollection> ReadFormAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return Task.FromResult<IFormCollection>(_ReadFormAsync);
}
}
}
| stratisproject/TCPServer | TCPServer/ServerImplemetation/TCPRequest.cs | C# | mit | 4,306 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c5d231db-9fb7-42cc-843f-72f9ca4ef087")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| sdanna/TeamcityTestSite | src/UnitTests/Properties/AssemblyInfo.cs | C# | mit | 1,394 |
<?php
namespace VirtualPersistAPI\VirtualPersistBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class VirtualPersistExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
}
| paul-m/VirtualPersistAPI | src/VirtualPersistAPI/VirtualPersistBundle/DependencyInjection/VirtualPersistExtension.php | PHP | mit | 903 |
import { Selector } from 'testcafe'
import { ROOT_URL, login } from '../e2e/utils'
// eslint-disable-next-line
fixture`imported data check`.beforeEach(async (t /*: TestController */) => {
await t.setNativeDialogHandler(() => true)
await t.navigateTo(`${ROOT_URL}/login`)
await login(t)
})
test('wait entry', async (t /*: TestController */) => {
await t
.expect(Selector('a').withText('Ask HN: single comment').exists)
.ok({ timeout: 20000 })
})
| reimagined/resolve | examples/ts/hacker-news/test/e2e-post-import/check-import.ts | TypeScript | mit | 463 |
---
layout: post
date: '2016-12-21'
title: "Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress "
category: Wedding Dress
tags: ["dress","full","floor","length","bride"]
image: http://www.starbrideapparel.com/21326-thickbox_default/compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress-.jpg
---
Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress
On Sales: **$195.594**
<a href="https://www.starbrideapparel.com/wedding-dress/8580-compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress--1463394479084.html"><amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/21326-thickbox_default/compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress-.jpg" alt="Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress 0" /></a>
<a href="https://www.starbrideapparel.com/wedding-dress/8580-compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress--1463394479084.html"><amp-img layout="responsive" width="600" height="600" src="//www.starbrideapparel.com/21327-thickbox_default/compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress-.jpg" alt="Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress 1" /></a>
Buy it: [Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress ](https://www.starbrideapparel.com/wedding-dress/8580-compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress--1463394479084.html "Compelling Strapless Sleeveless Full Back Floor Length Satin Sheath Wedding Dress ")
View more: [Wedding Dress](https://www.starbrideapparel.com/80-wedding-dress "Wedding Dress") | lignertys/lignertys.github.io | _posts/2016-12-21-compelling-strapless-sleeveless-full-back-floor-length-satin-sheath-wedding-dress.md | Markdown | mit | 1,814 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>vergerpc.config — Utilities for reading verge configuration files — verge-python 0.1.3 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '0.1.3',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="verge-python 0.1.3 documentation" href="index.html" />
<link rel="up" title="API reference" href="apireference.html" />
<link rel="prev" title="vergerpc.data — VERGE RPC service, data objects" href="vergerpc.data.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="vergerpc.data.html" title="vergerpc.data — VERGE RPC service, data objects"
accesskey="P">previous</a> |</li>
<li><a href="index.html">verge-python 0.1.3 documentation</a> »</li>
<li><a href="apireference.html" accesskey="U">API reference</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="module-vergerpc.config">
<span id="vergerpc-config-utilities-for-reading-verge-configuration-files"></span><h1><a class="reference internal" href="#module-vergerpc.config" title="vergerpc.config"><tt class="xref py py-mod docutils literal"><span class="pre">vergerpc.config</span></tt></a> — Utilities for reading verge configuration files<a class="headerlink" href="#module-vergerpc.config" title="Permalink to this headline">¶</a></h1>
<p>Utilities for reading verge configuration files.</p>
<dl class="function">
<dt id="vergerpc.config.read_config_file">
<tt class="descclassname">vergerpc.config.</tt><tt class="descname">read_config_file</tt><big>(</big><em>filename</em><big>)</big><a class="headerlink" href="#vergerpc.config.read_config_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a simple <tt class="docutils literal"><span class="pre">'='</span></tt>-delimited config file.
Raises <tt class="xref py py-const docutils literal"><span class="pre">IOError</span></tt> if unable to open file, or <tt class="xref py py-const docutils literal"><span class="pre">ValueError</span></tt>
if an parse error occurs.</p>
</dd></dl>
<dl class="function">
<dt id="vergerpc.config.read_default_config">
<tt class="descclassname">vergerpc.config.</tt><tt class="descname">read_default_config</tt><big>(</big><em>filename=None</em><big>)</big><a class="headerlink" href="#vergerpc.config.read_default_config" title="Permalink to this definition">¶</a></dt>
<dd><p>Read verge default configuration from the current user’s home directory.</p>
<p>Arguments:</p>
<ul class="simple">
<li><cite>filename</cite>: Path to a configuration file in a non-standard location (optional)</li>
</ul>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="vergerpc.data.html"
title="previous chapter"><tt class="docutils literal"><span class="pre">vergerpc.data</span></tt> — VERGE RPC service, data objects</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/vergerpc.config.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="vergerpc.data.html" title="vergerpc.data — VERGE RPC service, data objects"
>previous</a> |</li>
<li><a href="index.html">verge-python 0.1.3 documentation</a> »</li>
<li><a href="apireference.html" >API reference</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2016, verge-python developers.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.1.
</div>
</body>
</html> | vergecurrency/verge-python | doc/vergerpc.config.html | HTML | mit | 5,858 |
---
published: true
layout: post
title: "LAHacks: The most bizarre hackathon experience in my life"
quote: My 10th hackathon.
image:
url: "/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1685.jpg"
source: null
color: ""
posted: Published
video: false
comments: true
---
It was 2am, my team and I were wandering around the streets, looking for wifi.
We visited Starbucks before that opened 24/7 around the university area. Unfortunately it was crowded with homeless people and part of the area inside the coffee house was closed.
So we kept walking and explored the nearby hotels. Thanks to the very kind front desk staff, we crushed at Vintage Westwood Horizons’ hotel lobby at 3 in the morning because the WiFi connection got cut off at Pauley Pavilion. The internet was back at that time after LAHacks organizer announced it on Twitter, but we were too lazy to walk back so we pulled out our laptop and worked there.
I worked a little, and tried to get some sleep. The journey from Seattle - Los Angeles - UCLA was tiring. Dylan woke me up at 6am and we walked back to Pauley.
## We met on Twitter
Arik, Dylan, Cary and I formed our team through Twitter. I tweeted to LAHacks organizer and they retweeted my tweet. Arik is a student flying from Tel Aviv and LAHacks was his last event he attended in the United States; Cary and Dylan are both computer science major at Cal Poly Pomona. <br>
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/twitter.png" width="100%" description="" %}
## The Design behind SnapChess
Mystery guest speaker, Evan Spiegel, CEO of Snapchat made [a deep but great speech](https://twitter.com/adithyaiscool/status/454854832205996032) about privacy on the stage([Keynote available at Scribd](http://www.scribd.com/doc/217768898/2014-LA-Hacks-Keynote)). Our idea was to make a parody out of it — so we built Snapchess within 36 hours, a democracy-mode chess game matchmaking web application. You have 10 seconds to decide your next move with your alliance. To make it more interesting and relevant to the audience, I had the idea of putting UCLA and USC in this game, since there is a rivalry between the two. And even better, you can hack the game — play on behalf of your enemy, make all the wrong moves, and completely ruins your enemy’s game.
I was inspired by a [Dribbble shot](https://dribbble.com/shots/710449-ursa-delaunay) using [Delaunay Raster script](http://www.creatogether.com/ai-delaunay-brush/), but unfortunately Scriptographer is not available on CS6 due to [Adobe’s automatic wrapping of native API issue](http://scriptographer.org/news/the-future-of-scriptographer-is-paper-js/). I tweeted Tomás, the owner of the Dribbble shot. He responded promptly and suggested me to use [Dmesh](http://dmesh.thedofl.com/) instead. I explored to use the tool for the first time, and the result was surprisingly beautiful.
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Kodiak-Bear-small.jpg" width="100%" description="Original image of the bear I googled on the web. I do not own the copyright of this image." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-27 at 12.54.56 AM.png" width="100%" description="Process for converting in Dmesh." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-12 at 12.57.25 PM.png" width="100%" description="Working on Illustrator to take out the points and refine the design." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/bear-01.png" width="100%" description="Cleaned up version of the bear mascot for UCLA." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/bear-final.png" width="100%" description="Final version of the UCLA bear with color scheme tweaks." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Usc_football_logo.gif" width="50%" description="I asked a guy from USC and he told me the trojans are more famous about the traveller. Apparently no one cares about the traveller mascot but I decided to use it anyway." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-12 at 4.23.00 PM.png" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/trojan-final-01.png" width="100%" description="Color scheme is tweaked and here’s the final version for USC mascot." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/logo-01.png" width="100%" description="Final version of logo for Snapchess" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-12 at 11.53.31 PM.png" width="100%" description="Screenshot of the front page before I worked on the CSS styling. The links work." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-13 at 3.00.35 AM.png" width="100%" description="I used Bootplus framework and apply the design for the frontpage." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-12 at 5.23.39 PM.png" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-13 at 1.40.13 AM.png" width="100%" description="PHP master Arik was debugging on the game page. This was the screenshot before styling." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/Screen Shot 2014-04-27 at 1.04.29 AM.png" width="100%" description="Game page integrated with homepage design and CSS styling." %}
<iframe width="100%" height="360" src="//www.youtube.com/embed/guKuQJ4Qx_0" frameborder="0" allowfullscreen></iframe>
{% include image.html url="" width="0" description="Demo of Snapchess. I’m sorry if you don’t like Electronic Music :/ http://youtu.be/guKuQJ4Qx_0" %}
## The End
We had an expo after the hackathon was over and we were lining up on the table demoing our hacks. It was like a little SXSW at the event and I really like the idea. One of the feedback we received, which I think is helpful — is to create a login system which enables users to play based on weight and priority if you make the right moves most of the times.
We did not end up winning and I have expected that, since we did not use any of the sponsor’s API. Is SnapChess solving a big problem? No. But there’s currently no matchmaking for chess board game on the web right now([Twitch Plays Pokemon](http://www.twitch.tv/twitchplayspokemon) for Chess). Is it fun? I would say yes.
Crushing at the hotel lobby at 3 in the morning and sleeping under the staircase at Pauley Pavilion — I had the most bizarre yet fun experience by attending the largest hackathon in my life(hacking with 1400 people!). I am really thankful for the organizers to make the event all possible, especially the prompt respond on Twitter.
Achievement unlocked.
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1626.jpg" width="100%" description="Meeting Dylan and Arik for the first time after I flew in from Seattle on Friday afternoon." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1628.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1635.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1640.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1643.jpg" width="100%" description="From left to right: Arik, Cary, Dylan and Dylan’s cousin." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1644.jpg" width="100%" description="Waiting in the queue before entering Pauley." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1652.jpg" width="100%" description="LAHacks is the Disneyland of hackathons. Yes you need a wristband to go in." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1653.jpg" width="100%" description="Crushing and coding at the hotel lobby at 3 in the morning." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1654.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1662.jpg" width="100%" description="In-And-Out Burger near UCLA." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1663.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1664.jpg" width="100%" description="Having dinner with Arik at BBQ Chicken." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1665.jpg" width="100%" description="We skipped the Chipotle provided by LAHacks. That was worth it." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1667.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1672.jpg" width="100%" description="Alexis Ohanian and I founded Raddit, a redesigned version of Reddit 2.0 during LAHacks. It was pretty rad." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1673.jpg" width="100%" description="Just happy to get my book signed. When Alexis came to UW, I was at HackAtBrown hackathon. When he came to Brown University, I was back to UW. So finally we met." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1676.jpg" width="100%" description="Swallow pizza, drink red bull, and print all fibonacci number using python. “Disqualified, memory leaks.”" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1679.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1681.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1683.jpg" width="100%" description="Adib and I formed a team during the first hackathon in my life — Mega CodeDay Seattle and we won 1st place. Now is my 10th hackathon. Time flies." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1685.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1686.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1688.jpg" width="100%" description="Arik, the PHP master and me." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1690.jpg" width="100%" description="Demoing at the expo." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1691.jpg" width="100%" description="Tred team demoed the Oculus Rift Treadmill system to let you physically walk in your virtual world. They won 1st place at LAHacks and the team members are Shariq Hashme, Charlie Hulcher, and Jake Rye. Youtube video: http://youtu.be/XcX1uGFR6SE" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1692.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1693.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1694.jpg" width="100%" description="Table#38: 15 years old highschool freshman made Gorrila Warfare shooting game." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1695.jpg" width="100%" description="Table #31: Game maps your finger with touchdevelop using Makey makey and picks up potatoes." %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1703.jpg" width="100%" description="Table #32: Moozik lets users to type in their favorite artist and explore new music with similar genre. Built w/ gracenote & @rdio api" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1706.jpg" width="100%" description="Table #28: Crowdbox crowsources songs by letting users to vote on songs to be played in events" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1708.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1710.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1711.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1713.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1715.jpg" width="100%" description="" %}
{% include image.html url="/media/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life/IMG_1747.jpg" width="100%" description="" %}
<br>
*This post is originally published at [Medium.com](https://medium.com/p/9ff0e33a98e3), but it is a shorter version with no additional pictures.*
*Feel free to send me a tweet on Twitter if you have any feedback for me ☺*
Demo: [http://snapchess.co](http://snapchess.co)
Feel free to fork: [https://github.com/lcdvirgo/snapchess](https://github.com/lcdvirgo/snapchess)
ChallengePost: [http://lahacks.challengepost.com/submissions/22803-snapchess](http://lahacks.challengepost.com/submissions/22803-snapchess)
LA Weekly coverage: [http://www.laweekly.com/informer/2014/04/12/ucla-hosts-biggest-hackathon-in-history](http://www.laweekly.com/informer/2014/04/12/ucla-hosts-biggest-hackathon-in-history)
| lcdvirgo/lcdvirgo.github.io | _posts/2014-05-01-lahacks-the-most-bizarre-hackathon-experience-in-my-life.md | Markdown | mit | 15,312 |
<div itemprop="description" class="col-12">
<div [innerHTML]="description | sanitizeHtml"></div>
</div>
| aviabird/angularspree | src/app/product/components/product-detail-page/product-description/product-description.component.html | HTML | mit | 106 |
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; only version 2 of the License is applicable.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# This plugin is to monitor queue lengths in Redis. Based on redis_info.py by
# Garret Heaton <powdahound at gmail.com>, hence the GPL at the top.
import collectd
from contextlib import closing, contextmanager
import socket
# Host to connect to. Override in config by specifying 'Host'.
REDIS_HOST = 'localhost'
# Port to connect on. Override in config by specifying 'Port'.
REDIS_PORT = 6379
# Verbose logging on/off. Override in config by specifying 'Verbose'.
VERBOSE_LOGGING = False
# Queue names to monitor. Override in config by specifying 'Queues'.
QUEUE_NAMES = []
def fetch_queue_lengths(queue_names):
"""Connect to Redis server and request queue lengths.
Return a dictionary from queue names to integers.
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((REDIS_HOST, REDIS_PORT))
log_verbose('Connected to Redis at %s:%s' % (REDIS_HOST, REDIS_PORT))
except socket.error, e:
collectd.error('redis_queues plugin: Error connecting to %s:%d - %r'
% (REDIS_HOST, REDIS_PORT, e))
return None
queue_lengths = {}
with closing(s) as redis_socket:
for queue_name in queue_names:
log_verbose('Requesting length of queue %s' % queue_name)
redis_socket.sendall('llen %s\r\n' % queue_name)
with closing(redis_socket.makefile('r')) as response_file:
response = response_file.readline()
if response.startswith(':'):
try:
queue_lengths[queue_name] = int(response[1:-1])
except ValueError:
log_verbose('Invalid response: %r' % response)
else:
log_verbose('Invalid response: %r' % response)
return queue_lengths
def configure_callback(conf):
"""Receive configuration block"""
global REDIS_HOST, REDIS_PORT, VERBOSE_LOGGING, QUEUE_NAMES
for node in conf.children:
if node.key == 'Host':
REDIS_HOST = node.values[0]
elif node.key == 'Port':
REDIS_PORT = int(node.values[0])
elif node.key == 'Verbose':
VERBOSE_LOGGING = bool(node.values[0])
elif node.key == 'Queues':
QUEUE_NAMES = list(node.values)
else:
collectd.warning('redis_queues plugin: Unknown config key: %s.'
% node.key)
log_verbose('Configured with host=%s, port=%s' % (REDIS_HOST, REDIS_PORT))
for queue in QUEUE_NAMES:
log_verbose('Watching queue %s' % queue)
if not QUEUE_NAMES:
log_verbose('Not watching any queues')
def read_callback():
log_verbose('Read callback called')
queue_lengths = fetch_queue_lengths(QUEUE_NAMES)
if queue_lengths is None:
# An earlier error, reported to collectd by fetch_queue_lengths
return
for queue_name, queue_length in queue_lengths.items():
log_verbose('Sending value: %s=%s' % (queue_name, queue_length))
val = collectd.Values(plugin='redis_queues')
val.type = 'gauge'
val.type_instance = queue_name
val.values = [queue_length]
val.dispatch()
def log_verbose(msg):
if not VERBOSE_LOGGING:
return
collectd.info('redis plugin [verbose]: %s' % msg)
# register callbacks
collectd.register_config(configure_callback)
collectd.register_read(read_callback)
| alphagov/govuk-puppet | modules/collectd/files/usr/lib/collectd/python/redis_queues.py | Python | mit | 4,100 |
from .DiscreteFactor import State, DiscreteFactor
from .CPD import TabularCPD
from .JointProbabilityDistribution import JointProbabilityDistribution
__all__ = ['TabularCPD',
'DiscreteFactor',
'State'
]
| khalibartan/pgmpy | pgmpy/factors/discrete/__init__.py | Python | mit | 236 |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dev to DevOps</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="Hakim El Hattab">
<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.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="css/reveal.min.css">
<link rel="stylesheet" href="css/theme/sky.css" id="theme">
<link rel="stylesheet" href="css/dev2devops.css">
<!-- For syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- If the query includes 'print-pdf', use the PDF print sheet -->
<script>
document.write( '<link rel="stylesheet" href="css/print/' + ( window.location.search.match( /print-pdf/gi ) ? 'pdf' : 'paper' ) + '.css" type="text/css" media="print">' );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class='screen-logo'>
<div style='position: absolute; left: 20px; bottom: 20px; opacity: 0.5;'>
<img src='img/constant-contact-logo.png' width='250'>
</div>
</div>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h3>Intro to DevOps</h3>
<p>Hi, my name is Dinshaw.</p>
</section>
<section>
<h2>Computers</h2>
<p>The cause of – and the solution to – all of life's problems.</p>
</section>
<section>
<h2>A Brief History of Computing</h2>
</section>
<section>
<img src="img/colosus.jpg">
<h3>Mainframe</h3>
</section>
<section>
<img src="img/punch-cards.jpg">
<h3>Punch Cards</h3>
</section>
<section>
<img src="img/computer.jpg">
<h3>Personal Computers</h3>
</section>
<section class='the-wall-goes-up'>
<h3><span>Users . . .</span> The Wall <span>. . . Operations</span></h3>
</section>
<section>
<img src="img/patrick.jpg">
<h3>Patrick Dubois</h3>
<p>The 'Godfather' of DevOps</p>
</section>
<section>
<h3>10+ Deploys Per Day:</h3>
<h3>Dev and Ops Cooperation at Flickr</h3>
<p>John Allspaw and Paul Hammond</p>
<p>@ Velocity Conference 2009, San Jose</p>
</section>
<section>
<img src="img/spock-scotty.jpg">
</section>
<section>
<h1>#devops</h1>
</section>
<section>
<img src='img/culture.jpg'>
<h3>Culture</h3>
</section>
<section>
<img src='img/computer.jpg'>
<h3>Tools</h3>
</section>
<section>
<h3>... habits [tools & culture] that allow us to survive in <em><strong>The Danger Zone</strong></em>.</h3>
</section>
<section>
<h3>TurboTax</h3>
<p>165 new-feature experiments in the 3 month tax season</p>
<p><a href="http://network.intuit.com/2011/04/20/leadership-in-the-agile-age/">Economist conference 2011</a></p>
</section>
<section>
<h3>Puppet: State of DevOps Report</h3>
<p>'DevOps' up 50% on Linkedin keyword searches</p>
</section>
<section>
<h3>Puppet: What is a DevOps Engineer?</h3>
<ul>
<li class='fragment'>Coding/Scripting</li>
<li class='fragment'>Strong grasp of automation tools</li>
<li class='fragment'>Process re-engineering</li>
<li class='fragment'>A focus on business outcomes</li>
<li class='fragment'>Communication & Collaboration</li>
</ul>
</section>
<section>
<h2>Questions?</h2>
</section>
<section>
<h2>Puppet & Chef</h2>
<ul>
<li>Configuration Management</li>
<li>Portable</li>
<li>Repeatable</li>
</ul>
</section>
<section>
<h2>Puppet</h2>
<ul>
<li>http://puppetlabs.com/</li>
<li>Ruby-like</li>
<li>Modules @ Puppet Forge</li>
</ul>
<pre>
<code>
package { "gtypist":
ensure => installed,
provider => homebrew,
}
package { "redis":
ensure => installed,
provider => homebrew,
}
</code>
</pre>
</section>
<section>
<h2>Chef</h2>
<ul>
<li>http://www.getchef.com/</li>
<li>Opscode</li>
<li>Ruby</li>
<li>Cookbooks @ Opscode Community</li>
</ul>
<pre>
<code>
package "mysql" do
action :install
end
package "redis" do
action :install
end
</code>
</pre>
</section>
<section>
<h2>Vagrant</h2>
<p>http://www.vagrantup.com/</p>
<pre>
<code>
Vagrant.configure do |config|
config.vm.provision "puppet" do |puppet|
puppet.manifests_path = "my_manifests"
puppet.manifest_file = "default.pp"
end
end
</code>
</pre>
</section>
<section>
<h2>You build it; you run it.</h2>
<p>Deliver working code AND the environment it runs in.</p>
</section>
<section>
<h2>T.D.D.</h2>
<div>
<blockquote>
"If you tell the truth, you don't have to remember anything."
</blockquote>
<small class="author">- Mark Twain</small>
</div>
<p>Dev and Test are no longer separable</p>
</section>
<section>
<h2>What we need from Ops</h2>
<ul>
<li class='fragment'>One button environment</li>
<li class='fragment'>One button deploy</li>
</ul>
</section>
<section>
<h3>First Steps:</h3>
<ul>
<li class='fragment'>Automate something simple</li>
<ul>
<li class='fragment'>White space</li>
<li class='fragment'>Dev Log rotation</li>
<li class='fragment'><a href="http://dotfiles.github.io/">.Dotfiles</a></li>
</ul>
<li class='fragment'>Automate something not-so-simple</li>
<ul>
<li class='fragment'>Development machine configuration</li>
<li class='fragment'>Production configuration</li>
</ul>
</ul>
</section>
<section>
<h3>Questions?</h3>
</section>
<section>
<h2>Google SRE</h2>
<p class='fragment'>Hand-off Readiness Review</p>
<ul>
<li class='fragment'>Types/Frequency of defects</li>
<li class='fragment'>Maturity of monitoring</li>
<li class='fragment'>Release process</li>
</ul>
</section>
<section>
<h2><a href="http://techblog.netflix.com/2012/07/chaos-monkey-released-into-wild.html">Netflix: Chaos Monkey</a></h2>
<p>April 21st, 2011 Amazon Web Service outage</p>
<p>Netfilx maintained availability</p>
</section>
<section>
<h2><a href="https://blog.twitter.com/2010/murder-fast-datacenter-code-deploys-using-bittorrent">Twitter Murder!</a></h2>
<p class='fragment'>40 minute to 12 seconds!</p>
</section>
<section>
<h2><a href="http://www.youtube.com/watch?v=-LxavzqLHj8">ChatOps at Github</a></h2>
<p>Automating common operational tasks with Hu-Bot</p>
<img src='img/hu-bot.jpg'>
</section>
<section>
<h3>
<a href='http://assets.en.oreilly.com/1/event/60/Velocity%20Culture%20Presentation.pdf'>Amazon @ O'rily Velocity Conf. 2011</a>
</h3>
<ul>
<li class='fragment'>A deploy every 11.6 seconds</li>
<li class='fragment'>Max deployments per hour: 10,000</li>
<li class='fragment'>30,000 hosts simultaneously receiving a deployment</li>
</ul>
</section>
<section class='links'>
<ul>
<li><a href="http://www.devopsdays.org/">DevOpsDays</a></li>
<li><a href='http://velocityconf.com/velocity2009'>Velocity Conference 2009, San Jose</a></li>
<li><a href='http://velocityconference.blip.tv/file/2284377/'>10+ Deploys Per Day: Dev and Ops Cooperation at Flickr</a></li>
<li><a href='http://continuousdelivery.com/2012/10/theres-no-such-thing-as-a-devops-team/'>No such thing as a DevOps team</a></li>
<li><a href='http://www.youtube.com/watch?v=disjFj4ruHg'>Why We Need DevOps Now</a></li>
<li><a href='http://info.puppetlabs.com/2013-state-of-devops-report.html'>State of DevOps 2013 - Puppet Report</a></li>
<li><a href="http://network.intuit.com/2011/04/20/leadership-in-the-agile-age/">Scott Cook on TurboTax @ Economist conference 2011</a></li>
<li><a href="http://dotfiles.github.io/">.Dotfiles</a></li>
<li><a href="http://docs.puppetlabs.com/learning/">Learning Puppet</a></li>
<li><a href="http://forge.puppetlabs.com/">Puppet Forge</a></li>
<li><a href='http://boxen.github.com/'>Boxen</a></li>
<li><a href="http://vimeo.com/61172067">Boxen presentation: Managing an army of laptops</a></li>
<li><a href='http://www.opscode.com/chef/'>Opscode</a></li>
<li><a href="http://docs.opscode.com/">Learning Chef</a></li>
<li><a href="https://github.com/opscode-cookbooks">Chef Cookbooks</a></li>
<li><a href='http://www.youtube.com/watch?v=ZC91gZv-Uao'>Chef intro: TDDing tmux</a></li>
<li><a href="http://techblog.netflix.com/2012/07/chaos-monkey-released-into-wild.html">Netflix: Chaos Monkey</a></li>
<li><a href="https://blog.twitter.com/2010/murder-fast-datacenter-code-deploys-using-bittorrent">Twitter Murder!</a></li>
<li><a href="http://www.youtube.com/watch?v=-LxavzqLHj8">ChatOps at Github</a></li>
<li><a href="http://assets.en.oreilly.com/1/event/60/Velocity%20Culture%20Presentation.pdf">Amazon: A deploy every 11 seconds slides</a></li>
<li><a href='http://vimeo.com/61172067'>Managing an Army of Laptops with Puppet</a></li>
<li><a href='http://www.youtube.com/watch?v=ZC91gZv-Uao'>TDDing tmux</a></li>
</ul>
</section>
<section>
<p>Intro to DevOps</p>
<p>Dinshaw Gobhai | <a href="mailto:[email protected]">[email protected]</a></p>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/fade/none
// Optional libraries used to extend on reveal.js
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
// { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
// { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } },
// { src: 'plugin/search/search.js', async: true, condition: function() { return !!document.body.classList; } }
// { src: 'plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
</script>
</body>
</head>
</html>
| dinshaw/intro-to-devops | index.html | HTML | mit | 13,086 |
/*
Ql builtin and external frmt command.
format text
*/
package frmt
import (
"clive/cmd"
"clive/cmd/opt"
"clive/nchan"
"clive/zx"
"errors"
"fmt"
"io"
"strings"
"unicode"
)
type parFmt {
rc chan string
ec chan bool
}
func startPar(out io.Writer, indent0, indent string, max int) *parFmt {
rc := make(chan string)
ec := make(chan bool, 1)
wc := make(chan string)
pf := &parFmt{rc, ec}
go func() {
for s := range rc {
if s == "\n" {
wc <- s
continue
}
words := strings.Fields(strings.TrimSpace(s))
for _, w := range words {
wc <- w
}
}
close(wc)
}()
go func() {
pos, _ := fmt.Fprintf(out, "%s", indent0)
firstword := true
lastword := "x"
for w := range wc {
if len(w) == 0 {
continue
}
if w == "\n" {
fmt.Fprintf(out, "\n")
firstword = true
pos = 0
continue
}
if pos+len(w)+1 > max {
fmt.Fprintf(out, "\n")
pos, _ = fmt.Fprintf(out, "%s", indent)
firstword = true
}
if !firstword && len(w)>0 && !unicode.IsPunct(rune(w[0])) {
lastr := rune(lastword[len(lastword)-1])
if !strings.ContainsRune("([{", lastr) {
fmt.Fprintf(out, " ")
pos++
}
}
fmt.Fprintf(out, "%s", w)
pos += len(w)
firstword = false
lastword = w
}
if !firstword {
fmt.Fprintf(out, "\n")
}
close(ec)
}()
return pf
}
func (pf *parFmt) WriteString(s string) {
pf.rc <- s
}
func (pf *parFmt) Close() {
if pf == nil {
return
}
close(pf.rc)
<-pf.ec
}
type xCmd {
*cmd.Ctx
*opt.Flags
wid int
}
func tabsOf(s string) int {
for i := 0; i < len(s); i++ {
if s[i] != '\t' {
return i
}
}
return 0
}
func (x *xCmd) RunFile(d zx.Dir, dc <-chan []byte) error {
if dc == nil {
return nil
}
rc := nchan.Lines(dc, '\n')
var pf *parFmt
ntabs := 0
tabs := ""
doselect {
case <-x.Intrc:
close(rc, "interrupted")
pf.Close()
return errors.New("interrupted")
case s, ok := <-rc:
if !ok {
pf.Close()
return cerror(rc)
}
if s=="\n" || s=="" {
pf.Close()
pf = nil
x.Printf("\n")
continue
}
nt := tabsOf(s)
if nt != ntabs {
pf.Close()
pf = nil
ntabs = nt
tabs = strings.Repeat("\t", ntabs)
}
if pf == nil {
pf = startPar(x.Stdout, tabs, tabs, x.wid)
}
pf.WriteString(s)
}
pf.Close()
if err := cerror(rc); err != nil {
return err
}
return nil
}
func Run(c cmd.Ctx) (err error) {
argv := c.Args
x := &xCmd{Ctx: &c}
x.Flags = opt.New("{file}")
x.Argv0 = argv[0]
x.NewFlag("w", "wid: set max line width", &x.wid)
args, err := x.Parse(argv)
if err != nil {
x.Usage(x.Stderr)
return err
}
if x.wid < 10 {
x.wid = 70
}
if cmd.Ns == nil {
cmd.MkNS()
}
return cmd.RunFiles(x, args...)
}
| sbinet-staging/clive | cmd/oldql/frmt/frmt.go | GO | mit | 2,706 |
({
baseUrl: "../linesocial/public/js",
paths: {
jquery: "public/js/libs/jquery-1.9.1.js"
},
name: "main",
out: "main-built.js"
}) | jackygrahamez/LineSocialPublic | build.js | JavaScript | mit | 157 |
<?php
namespace Usolv\TrackingBundle\Form\Model;
use Doctrine\Common\Collections\ArrayCollection;
class TimeRecordSearch
{
protected $project;
public function setProject($project)
{
$this->project = $project;
return $this;
}
public function getProject()
{
return $this->project;
}
}
| LeQuangAnh/USVTracking | src/Usolv/TrackingBundle/Form/Model/TimeRecordSearch.php | PHP | mit | 325 |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Fieldset, Layout
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from django.db import transaction
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from django_filters import FilterSet
from easy_select2 import Select2
from crispy_layout_mixin import form_actions, to_row
from utils import (TIPO_TELEFONE, YES_NO_CHOICES, get_medicos,
get_or_create_grupo)
from .models import Especialidade, EspecialidadeMedico, Usuario
class EspecialidadeMedicoFilterSet(FilterSet):
class Meta:
model = EspecialidadeMedico
fields = ['especialidade']
def __init__(self, *args, **kwargs):
super(EspecialidadeMedicoFilterSet, self).__init__(*args, **kwargs)
row1 = to_row([('especialidade', 12)])
self.form.helper = FormHelper()
self.form.helper.form_method = 'GET'
self.form.helper.layout = Layout(
Fieldset(_('Pesquisar Médico'),
row1, form_actions(save_label='Filtrar'))
)
class MudarSenhaForm(forms.Form):
nova_senha = forms.CharField(
label="Nova Senha", max_length=30,
widget=forms.PasswordInput(
attrs={'class': 'form-control form-control-lg',
'name': 'senha',
'placeholder': 'Nova Senha'}))
confirmar_senha = forms.CharField(
label="Confirmar Senha", max_length=30,
widget=forms.PasswordInput(
attrs={'class': 'form-control form-control-lg',
'name': 'confirmar_senha',
'placeholder': 'Confirmar Senha'}))
class LoginForm(AuthenticationForm):
username = forms.CharField(
label="Username", max_length=30,
widget=forms.TextInput(
attrs={'class': 'form-control form-control-lg',
'name': 'username',
'placeholder': 'Usuário'}))
password = forms.CharField(
label="Password", max_length=30,
widget=forms.PasswordInput(
attrs={'class': 'form-control',
'name': 'password',
'placeholder': 'Senha'}))
class UsuarioForm(ModelForm):
# Usuário
password = forms.CharField(
max_length=20,
label=_('Senha'),
widget=forms.PasswordInput())
password_confirm = forms.CharField(
max_length=20,
label=_('Confirmar Senha'),
widget=forms.PasswordInput())
class Meta:
model = Usuario
fields = ['username', 'email', 'nome', 'password', 'password_confirm',
'data_nascimento', 'sexo', 'plano', 'tipo', 'cep', 'end',
'numero', 'complemento', 'bairro', 'referencia',
'primeiro_telefone', 'segundo_telefone']
widgets = {'email': forms.TextInput(
attrs={'style': 'text-transform:lowercase;'})}
def __init__(self, *args, **kwargs):
super(UsuarioForm, self).__init__(*args, **kwargs)
self.fields['primeiro_telefone'].widget.attrs['class'] = 'telefone'
self.fields['segundo_telefone'].widget.attrs['class'] = 'telefone'
def valida_igualdade(self, texto1, texto2, msg):
if texto1 != texto2:
raise ValidationError(msg)
return True
def clean(self):
if ('password' not in self.cleaned_data or
'password_confirm' not in self.cleaned_data):
raise ValidationError(_('Favor informar senhas atuais ou novas'))
msg = _('As senhas não conferem.')
self.valida_igualdade(
self.cleaned_data['password'],
self.cleaned_data['password_confirm'],
msg)
try:
validate_password(self.cleaned_data['password'])
except ValidationError as error:
raise ValidationError(error)
return self.cleaned_data
@transaction.atomic
def save(self, commit=False):
usuario = super(UsuarioForm, self).save(commit)
# Cria User
u = User.objects.create(username=usuario.username, email=usuario.email)
u.set_password(self.cleaned_data['password'])
u.is_active = True
u.groups.add(get_or_create_grupo(self.cleaned_data['tipo'].descricao))
u.save()
usuario.user = u
usuario.save()
return usuario
class UsuarioEditForm(ModelForm):
# Primeiro Telefone
primeiro_tipo = forms.ChoiceField(
widget=forms.Select(),
choices=TIPO_TELEFONE,
label=_('Tipo Telefone'))
primeiro_ddd = forms.CharField(max_length=2, label=_('DDD'))
primeiro_numero = forms.CharField(max_length=10, label=_('Número'))
primeiro_principal = forms.TypedChoiceField(
widget=forms.Select(),
label=_('Telefone Principal?'),
choices=YES_NO_CHOICES)
# Primeiro Telefone
segundo_tipo = forms.ChoiceField(
required=False,
widget=forms.Select(),
choices=TIPO_TELEFONE,
label=_('Tipo Telefone'))
segundo_ddd = forms.CharField(required=False, max_length=2, label=_('DDD'))
segundo_numero = forms.CharField(
required=False, max_length=10, label=_('Número'))
segundo_principal = forms.ChoiceField(
required=False,
widget=forms.Select(),
label=_('Telefone Principal?'),
choices=YES_NO_CHOICES)
class Meta:
model = Usuario
fields = ['username', 'email', 'nome', 'data_nascimento', 'sexo',
'plano', 'tipo', 'cep', 'end', 'numero', 'complemento',
'bairro', 'referencia', 'primeiro_telefone',
'segundo_telefone']
widgets = {'username': forms.TextInput(attrs={'readonly': 'readonly'}),
'email': forms.TextInput(
attrs={'style': 'text-transform:lowercase;'}),
}
def __init__(self, *args, **kwargs):
super(UsuarioEditForm, self).__init__(*args, **kwargs)
self.fields['primeiro_telefone'].widget.attrs['class'] = 'telefone'
self.fields['segundo_telefone'].widget.attrs['class'] = 'telefone'
def valida_igualdade(self, texto1, texto2, msg):
if texto1 != texto2:
raise ValidationError(msg)
return True
def clean_primeiro_numero(self):
cleaned_data = self.cleaned_data
telefone = Telefone()
telefone.tipo = self.data['primeiro_tipo']
telefone.ddd = self.data['primeiro_ddd']
telefone.numero = self.data['primeiro_numero']
telefone.principal = self.data['primeiro_principal']
cleaned_data['primeiro_telefone'] = telefone
return cleaned_data
def clean_segundo_numero(self):
cleaned_data = self.cleaned_data
telefone = Telefone()
telefone.tipo = self.data['segundo_tipo']
telefone.ddd = self.data['segundo_ddd']
telefone.numero = self.data['segundo_numero']
telefone.principal = self.data['segundo_principal']
cleaned_data['segundo_telefone'] = telefone
return cleaned_data
@transaction.atomic
def save(self, commit=False):
usuario = super(UsuarioEditForm, self).save(commit)
# Primeiro telefone
tel = usuario.primeiro_telefone
tel.tipo = self.data['primeiro_tipo']
tel.ddd = self.data['primeiro_ddd']
tel.numero = self.data['primeiro_numero']
tel.principal = self.data['primeiro_principal']
tel.save()
usuario.primeiro_telefone = tel
# Segundo telefone
tel = usuario.segundo_telefone
if tel:
tel.tipo = self.data['segundo_tipo']
tel.ddd = self.data['segundo_ddd']
tel.numero = self.data['segundo_numero']
tel.principal = self.data['segundo_principal']
tel.save()
usuario.segundo_telefone = tel
# User
u = usuario.user
u.email = usuario.email
u.groups.remove(u.groups.first())
u.groups.add(get_or_create_grupo(self.cleaned_data['tipo'].descricao))
u.save()
usuario.save()
return usuario
class EspecialidadeMedicoForm(ModelForm):
medico = forms.ModelChoiceField(
queryset=get_medicos(),
widget=Select2(select2attrs={'width': '535px'}))
especialidade = forms.ModelChoiceField(
queryset=Especialidade.objects.all(),
widget=Select2(select2attrs={'width': '535px'}))
class Meta:
model = EspecialidadeMedico
fields = ['especialidade', 'medico']
| eduardoedson/scp | usuarios/forms.py | Python | mit | 8,823 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.