text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use Array.isArray() instead of lodash.
|
import sinon from "sinon";
import jQueryObject from "./jQueryObject";
const arrayEach = ( a, c ) => {
for ( let i = 0; i < a.length; i++ ) {
c( i, a[ i ] );
}
};
const objectEach = ( o, c ) => {
for ( let k in o ) {
if ( o.hasOwnProperty( k ) ) {
c( k, o[ k ] );
}
}
};
const jQuery = sinon.stub();
jQuery.ajax = sinon.stub();
jQuery.each = ( o = {}, c ) => Array.isArray( o ) ? arrayEach( o, c ) : objectEach( o, c );
jQuery.trim = ( a ) => a;
jQuery._restore = () => {
jQuery.reset().resetBehavior();
// TODO: On each call, return a fresh jQueryObject. Depends on something like sinon.stub().returnsCallbackResult()`.
jQuery.returns( new jQueryObject() );
};
jQuery._restore();
export default jQuery;
|
import * as _ from "lodash";
import sinon from "sinon";
import jQueryObject from "./jQueryObject";
const arrayEach = ( a, c ) => {
for ( let i = 0; i < a.length; i++ ) {
c( i, a[ i ] );
}
};
const objectEach = ( o, c ) => {
for ( let k in o ) {
if ( o.hasOwnProperty( k ) ) {
c( k, o[ k ] );
}
}
};
const jQuery = sinon.stub();
jQuery.ajax = sinon.stub();
jQuery.each = ( o = {}, c ) => _.isArray( o ) ? arrayEach( o, c ) : objectEach( o, c );
jQuery.trim = ( a ) => a;
jQuery._restore = () => {
jQuery.reset().resetBehavior();
// TODO: On each call, return a fresh jQueryObject. Depends on something like sinon.stub().returnsCallbackResult()`.
jQuery.returns( new jQueryObject() );
};
jQuery._restore();
export default jQuery;
|
[TASK] Remove logger.error as default callback to deposit finished job.
|
var depositCallbackJob = require(__dirname+'/../jobs/deposit_completion_callback.js');
var OutgoingPayment = require(__dirname+'/outgoing_payment.js');
function OutgoingPaymentProcessor(payment) {
this.outgoingPayment = new OutgoingPayment(payment);
logger.info('payment:outgoing:recorded', payment.toJSON());
}
OutgoingPaymentProcessor.prototype = {
processOutgoingPayment: function(callback) {
var self = this;
self.outgoingPayment.processOutgoingPayment(function(error, record) {
if (error) {
logger.error('payment:outgoing:error', error);
depositCallbackJob.perform([record.id]);
setTimeout(callback, 2000);
} else {
depositCallbackJob.perform([record.id]);
callback();
}
});
}
};
module.exports = OutgoingPaymentProcessor;
|
var depositCallbackJob = require(__dirname+'/../jobs/deposit_completion_callback.js');
var OutgoingPayment = require(__dirname+'/outgoing_payment.js');
function OutgoingPaymentProcessor(payment) {
this.outgoingPayment = new OutgoingPayment(payment);
logger.info('payment:outgoing:recorded', payment);
}
OutgoingPaymentProcessor.prototype = {
processOutgoingPayment: function(callback) {
var self = this;
self.outgoingPayment.processOutgoingPayment(function(error, record) {
if (error) {
logger.error('payment:outgoing:error', error);
depositCallbackJob.perform([record.id], logger.error);
setTimeout(callback, 2000);
} else {
depositCallbackJob.perform([record.id], logger.error);
callback();
}
});
}
};
module.exports = OutgoingPaymentProcessor;
|
Move jquery.colorPicker images to layout resource
|
/**
* @class CM_FormField_Color
* @extends CM_FormField_Abstract
*/
var CM_FormField_Color = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Color',
ready: function() {
var field = this;
/*
* mColorPicker's "replace" option cannot be set to false here (too late)
* Set it within mColorPicker!
*/
$.fn.mColorPicker.init.replace = false;
$.fn.mColorPicker.init.allowTransparency = false;
$.fn.mColorPicker.init.showLogo = false;
$.fn.mColorPicker.init.enhancedSwatches = false;
this.$('input').mColorPicker({
"imageFolder": cm.getUrlResource('layout', 'img/jquery.mColorPicker/')
});
$("#mColorPickerFooter").remove();
$("#mColorPicker").height(158);
this.$('input').change(function() {
field.trigger('change');
});
}
});
|
/**
* @class CM_FormField_Color
* @extends CM_FormField_Abstract
*/
var CM_FormField_Color = CM_FormField_Abstract.extend({
_class: 'CM_FormField_Color',
ready: function() {
var field = this;
/*
* mColorPicker's "replace" option cannot be set to false here (too late)
* Set it within mColorPicker!
*/
$.fn.mColorPicker.init.replace = false;
$.fn.mColorPicker.init.allowTransparency = false;
$.fn.mColorPicker.init.showLogo = false;
$.fn.mColorPicker.init.enhancedSwatches = false;
this.$('input').mColorPicker({
"imageFolder": cm.getUrlStatic() + '/img/jquery.mColorPicker/'
});
$("#mColorPickerFooter").remove();
$("#mColorPicker").height(158);
this.$('input').change(function() {
field.trigger('change');
});
}
});
|
Send WARN alarms to ops-warn
|
/** @typedef {import('./index').EventBridgeCloudWatchAlarmsEvent} EventBridgeCloudWatchAlarmsEvent */
module.exports = {
/**
* @param {EventBridgeCloudWatchAlarmsEvent} event
* @returns {String} A Slack channel identifier
*/
channel(event) {
const name = event.detail.alarmName;
if (name.startsWith('FATAL')) {
return '#ops-fatal';
} else if (name.startsWith('ERROR')) {
return '#ops-error';
} else if (name.startsWith('WARN')) {
return '#ops-warn';
}
// } else if (name.startsWith('WARN')) {
// return '#ops-warn';
// } else if (name.startsWith('INFO')) {
// return '#ops-info';
// } else if (name.startsWith('CRITICAL')) {
// return '#ops-info';
// } else if (name.startsWith('MAJOR')) {
// return '#ops-info';
// } else if (name.startsWith('MINOR')) {
// return '#ops-info';
// }
return '#sandbox2';
},
};
|
/** @typedef {import('./index').EventBridgeCloudWatchAlarmsEvent} EventBridgeCloudWatchAlarmsEvent */
module.exports = {
/**
* @param {EventBridgeCloudWatchAlarmsEvent} event
* @returns {String} A Slack channel identifier
*/
channel(event) {
const name = event.detail.alarmName;
if (name.startsWith('FATAL')) {
return '#ops-fatal';
} else if (name.startsWith('ERROR')) {
return '#ops-error';
}
// } else if (name.startsWith('WARN')) {
// return '#ops-warn';
// } else if (name.startsWith('INFO')) {
// return '#ops-info';
// } else if (name.startsWith('CRITICAL')) {
// return '#ops-info';
// } else if (name.startsWith('MAJOR')) {
// return '#ops-info';
// } else if (name.startsWith('MINOR')) {
// return '#ops-info';
// }
return '#sandbox2';
},
};
|
Rename type tokens for clarity.
I always get this around the wrong way the first time.
|
/*
* Copyright 2008 the original author or authors.
*
* 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 org.gradle.api;
/**
* <p>A {@code Transformer} transforms objects of type.</p>
*
* <p>Implementations are free to return new objects or mutate the incoming value.</p>
*
* @param <OUT> The type the value is transformed to.
* @param <IN> The type of the value to be transformed.
*/
public interface Transformer<OUT, IN> {
/**
* Transforms the given object, and returns the transformed value.
*
* @param original The object to transform.
* @return The transformed object.
*/
OUT transform(IN original);
}
|
/*
* Copyright 2008 the original author or authors.
*
* 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 org.gradle.api;
/**
* <p>A {@code Transformer} transforms objects of type.</p>
*
* <p>Implementations are free to return new objects or mutate the incoming value.</p>
*
* @param <R> The type the value is transformed to.
* @param <I> The type of the value to be transformed.
*/
public interface Transformer<R, I> {
/**
* Transforms the given object, and returns the transformed value.
*
* @param original The object to transform.
* @return The transformed object.
*/
R transform(I original);
}
|
Tweak the findOneP function slightly
|
/**
* Dependencies
* --------------------------------------------------------------------------*/
var Promise = require('bluebird'),
_ = require('underscore');
/**
* Returns a promise of a document's save operation
*/
function saveP(doc) {
return Promise.promisify(doc.save, doc)()
.then(_.last);
}
/**
* Returns a promise of a document's remove operation
*/
function removeP(doc) {
return Promise.promisify(doc.remove, doc)()
.then(_.last);
}
/**
* Returns a promise of a Model's findOne operation, with an optional not found
* error message
*/
function findOneP(model, query, not_found_msg) {
var findOne = model.findOneAsync || Promise.promisify(model.findOne, model),
docP = findOne(query);
if(not_found_msg) {
return docP.then(function(doc) {
if(!doc) throw _.extend(new Error(not_found_msg), { status: 404 });
else return doc;
});
} else return docP;
}
function findByIdP(model, id, not_found_msg) {
return findOneP(model, id, not_found_msg);
}
module.exports = {
saveP: saveP,
removeP: removeP,
findOneP: findOneP,
findByIdP: findByIdP
};
|
/**
* Dependencies
* --------------------------------------------------------------------------*/
var Promise = require('bluebird'),
_ = require('underscore');
/**
* Returns a promise of a document's save operation
*/
function saveP(doc) {
return Promise.promisify(doc.save, doc)()
.then(_.last);
}
/**
* Returns a promise of a document's remove operation
*/
function removeP(doc) {
return Promise.promisify(doc.remove, doc)()
.then(_.last);
}
/**
* Returns a promise of a Model's findOne operation, with an optional not found
* error message
*/
function findOneP(model, query, not_found_msg) {
var findOne = Promise.promisify(model.findOne, model),
docP = findOne(query);
if(not_found_msg) {
return docP.then(function(doc) {
if(!doc){
throw _.extend(new Error(not_found_msg),
{ status: 404 });
} else return doc;
});
} else return docP;
}
function findByIdP(model, id, not_found_msg) {
return findOneP(model, id, not_found_msg);
}
module.exports = {
saveP: saveP,
removeP: removeP,
findOneP: findOneP,
findByIdP: findByIdP
};
|
Make set/getSourcePosition final on Node.
PiperOrigin-RevId: 304549770
|
/*
* Copyright 2015 Google Inc.
*
* 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 com.google.j2cl.ast;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.j2cl.ast.annotations.Visitable;
import com.google.j2cl.ast.processors.common.Processor;
import com.google.j2cl.common.SourcePosition;
/** A base class for Statement. */
@Visitable
public abstract class Statement extends Node implements HasSourcePosition, Cloneable<Statement> {
// unknown by default.
private SourcePosition sourcePosition;
public Statement(SourcePosition sourcePosition) {
setSourcePosition(sourcePosition);
}
@Override
public final SourcePosition getSourcePosition() {
return sourcePosition;
}
public final void setSourcePosition(SourcePosition sourcePosition) {
this.sourcePosition = checkNotNull(sourcePosition);
}
@Override
public abstract Statement clone();
@Override
public Node accept(Processor processor) {
return Visitor_Statement.visit(processor, this);
}
}
|
/*
* Copyright 2015 Google Inc.
*
* 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 com.google.j2cl.ast;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.j2cl.ast.annotations.Visitable;
import com.google.j2cl.ast.processors.common.Processor;
import com.google.j2cl.common.SourcePosition;
/** A base class for Statement. */
@Visitable
public abstract class Statement extends Node implements HasSourcePosition, Cloneable<Statement> {
// unknown by default.
private SourcePosition sourcePosition;
public Statement(SourcePosition sourcePosition) {
setSourcePosition(sourcePosition);
}
@Override
public SourcePosition getSourcePosition() {
return sourcePosition;
}
public void setSourcePosition(SourcePosition sourcePosition) {
this.sourcePosition = checkNotNull(sourcePosition);
}
@Override
public abstract Statement clone();
@Override
public Node accept(Processor processor) {
return Visitor_Statement.visit(processor, this);
}
}
|
Set id in insert query during inserts or update
|
/**
*
*/
package org.openforis.collect.persistence.jooq;
import java.sql.Connection;
import org.jooq.Record;
import org.jooq.Sequence;
import org.jooq.StoreQuery;
import org.jooq.TableField;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.idm.metamodel.PersistedSurveyObject;
/**
* @author S. Ricci
*
*/
public abstract class SurveyObjectMappingDSLContext<T extends PersistedSurveyObject> extends MappingDSLContext<T> {
private static final long serialVersionUID = 1L;
protected CollectSurvey survey;
public SurveyObjectMappingDSLContext(Connection conn,
TableField<?, Integer> idField,
Sequence<? extends Number> idSequence,
Class<T> clazz, CollectSurvey survey) {
super(conn, idField, idSequence, clazz);
this.survey = survey;
}
@Override
protected void fromObject(T o, StoreQuery<?> q) {
q.addValue(getIdField(), o.getId());
}
@Override
protected void fromRecord(Record r, T o) {
o.setId(r.getValue(getIdField()));
}
@Override
protected void setId(T entity, int id) {
entity.setId(id);
}
@Override
protected Integer getId(T entity) {
return entity.getId();
}
public CollectSurvey getSurvey() {
return survey;
}
}
|
/**
*
*/
package org.openforis.collect.persistence.jooq;
import java.sql.Connection;
import org.jooq.Record;
import org.jooq.Sequence;
import org.jooq.StoreQuery;
import org.jooq.TableField;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.idm.metamodel.PersistedSurveyObject;
/**
* @author S. Ricci
*
*/
public abstract class SurveyObjectMappingDSLContext<T extends PersistedSurveyObject> extends MappingDSLContext<T> {
private static final long serialVersionUID = 1L;
protected CollectSurvey survey;
public SurveyObjectMappingDSLContext(Connection conn,
TableField<?, Integer> idField,
Sequence<? extends Number> idSequence,
Class<T> clazz, CollectSurvey survey) {
super(conn, idField, idSequence, clazz);
this.survey = survey;
}
@Override
protected void fromObject(T o, StoreQuery<?> q) {
}
@Override
protected void fromRecord(Record r, T o) {
o.setId(r.getValue(getIdField()));
}
@Override
protected void setId(T entity, int id) {
entity.setId(id);
}
@Override
protected Integer getId(T entity) {
return entity.getId();
}
public CollectSurvey getSurvey() {
return survey;
}
}
|
Use query parameters through the python library
|
import unittest
import http.client
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
connRouter.close()
self.assertEqual(response.status, 404)
def test_200NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
params = {
'location': '/google',
'upstream': 'ttp://www.google.com/',
'ttl': '10'
}
connConfig.request("GET","/configure",params=params)
response = connConfig.getresponse()
print("Body:", response.read().decode("utf-8"),"\n")
#self.assertEqual(response.status, 200)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
#self.assertEqual(response.status, 200)
connRouter.close()
connConfig.close()
if __name__ == '__main__':
unittest.main()
|
import unittest
import http.client
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
connRouter.close()
self.assertEqual(response.status, 404)
def test_200NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connConfig.request("GET","/configure?location=/google&upstream=http://www.google.com&ttl=10")
response = connConfig.getresponse()
print("Body:", response.read().decode("utf-8"),"\n")
#self.assertEqual(response.status, 200)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
#self.assertEqual(response.status, 200)
connRouter.close()
connConfig.close()
if __name__ == '__main__':
unittest.main()
|
Include user and pwd to mongo url
|
var MongoClient = require('mongodb').MongoClient;
var jsonfile = require('jsonfile');
var _ = require('lodash');
var local = require('./config/local');
var mongoUrl = function (config) {
var u = config.user;
var pwd = config.password;
var h = config.host;
var p = config.port;
var d = config.database;
return 'mongodb://' + u + ':' + pwd + '@' + h + ':' + p + '/' + d;
};
var url = mongoUrl(local.tresdb_db);
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Connected correctly to server");
var locations = db.collection('locations');
var dumploc2mongoloc = function (loc) {
// Maybe unnecessary function.
return {
name: loc.name,
lat: loc.lat,
lng: loc.lng,
locator_id: loc._id
};
};
// Read locations from the dump
jsonfile.readFile('./data/dump.json', function (err, obj) {
if (err) throw err;
var locsToInsert = _.map(obj.locations, dumploc2mongoloc);
locations.insertMany(locsToInsert, function (err, result) {
if (err) throw err;
var n = result.result.n;
console.log(n + ' locations inserted successfully');
// Important to close after everything else. Close during insertion
// leads to error 'server instance pool was destroyed'.
db.close();
});
});
});
|
var MongoClient = require('mongodb').MongoClient;
var jsonfile = require('jsonfile');
var _ = require('lodash');
var local = require('./config/local');
var mongoUrl = function (config) {
var h = config.host;
var p = config.port;
var d = config.database;
return 'mongodb://' + h + ':' + p + '/' + d;
};
var url = mongoUrl(local.tresdb_db);
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Connected correctly to server");
var locations = db.collection('locations');
var dumploc2mongoloc = function (loc) {
// Maybe unnecessary function.
return {
name: loc.name,
lat: loc.lat,
lng: loc.lng,
locator_id: loc._id
};
};
// Read locations from the dump
jsonfile.readFile('./data/dump.json', function (err, obj) {
if (err) throw err;
var locsToInsert = _.map(obj.locations, dumploc2mongoloc);
locations.insertMany(locsToInsert, function (err, result) {
if (err) throw err;
var n = result.result.n;
console.log(n + ' locations inserted successfully');
// Important to close after everything else. Close during insertion
// leads to error 'server instance pool was destroyed'.
db.close();
});
});
});
|
Fix Projectile Entity position bug
|
package com.infinityraider.infinitylib.entity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.Packet;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.projectile.ThrowableProjectile;
import net.minecraft.world.level.Level;
public abstract class EntityThrowableBase extends ThrowableProjectile implements IBaseEntityImplementation<EntityThrowableBase> {
protected EntityThrowableBase(EntityType<? extends ThrowableProjectile> type, Level world) {
super(type, world);
}
protected EntityThrowableBase(EntityType<? extends ThrowableProjectile> type, Entity thrower) {
this(type, thrower.getLevel());
this.setPos(thrower.getX(), thrower.getEyeY() - (double)0.1F, thrower.getZ());
this.setOwner(thrower);
}
@Override
public final Packet<?> createSpawnPacket() {
return IBaseEntityImplementation.super.createSpawnPacket();
}
@Override
public final void addAdditionalSaveData(CompoundTag tag) {
super.addAdditionalSaveData(tag);
this.writeCustomEntityData(tag);
}
@Override
public final void readAdditionalSaveData(CompoundTag tag) {
super.readAdditionalSaveData(tag);
this.readCustomEntityData(tag);
}
}
|
package com.infinityraider.infinitylib.entity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.Packet;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.projectile.ThrowableProjectile;
import net.minecraft.world.level.Level;
public abstract class EntityThrowableBase extends ThrowableProjectile implements IBaseEntityImplementation<EntityThrowableBase> {
protected EntityThrowableBase(EntityType<? extends ThrowableProjectile> type, Level world) {
super(type, world);
}
protected EntityThrowableBase(EntityType<? extends ThrowableProjectile> type, Entity thrower) {
this(type, thrower.getLevel());
this.setOwner(thrower);
}
@Override
public final Packet<?> createSpawnPacket() {
return IBaseEntityImplementation.super.createSpawnPacket();
}
@Override
public final void addAdditionalSaveData(CompoundTag tag) {
super.addAdditionalSaveData(tag);
this.writeCustomEntityData(tag);
}
@Override
public final void readAdditionalSaveData(CompoundTag tag) {
super.readAdditionalSaveData(tag);
this.readCustomEntityData(tag);
}
}
|
Fix a bug when Stop button does not behaves as expected in selected browsers (Firefox, Opera)
Windows 7 64 bit
Opera 12.11
Firefox 16.0.2
|
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
media.pause();
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
|
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
|
Support spaces in track names
Fix URLs so that spaces in track names do not create fail.
|
# Copyright 2015 Thierry Carrez <thierry@openstack.org>
# All Rights Reserved.
#
# 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.
from django.conf.urls import patterns, url
from cheddar import views
urlpatterns = patterns(
'',
url(r'^$', views.index, name='index'),
url(r'^(\d+)$', views.trackindex),
url(r'^(\d+)/edit/(.+)$', views.modifysession),
url(r'^(\d+)/(.+)$', views.editsession),
url(r'^logout$', views.dologout),
url(r'^loggedout$', views.loggedout),
)
|
# Copyright 2015 Thierry Carrez <thierry@openstack.org>
# All Rights Reserved.
#
# 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.
from django.conf.urls import patterns, url
from cheddar import views
urlpatterns = patterns(
'',
url(r'^$', views.index, name='index'),
url(r'^(\d+)$', views.trackindex),
url(r'^(\d+)/edit/(\S+)$', views.modifysession),
url(r'^(\d+)/(\S+)$', views.editsession),
url(r'^logout$', views.dologout),
url(r'^loggedout$', views.loggedout),
)
|
Add function body around ref assignment
|
import md from 'components/md'
const Refs = () => md`
## Refs
Passing a \`ref\` prop to a styled component will give you an instance of
the \`StyledComponent\` wrapper, but not to the underlying DOM node.
This is due to how refs work.
It's not possible to call DOM methods, like \`focus\`, on our wrappers directly.
To get a ref to the actual, wrapped DOM node, pass the callback to the \`innerRef\` prop instead.
> We don't support string refs (i.e. \`innerRef="node"\`), since they're already deprecated in React.
This example uses \`innerRef\` to save a ref to the styled input and focuses it once the user
hovers over it.
\`\`\`react
const Input = styled.input\`
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
\`;
class Form extends React.Component {
render() {
return (
<Input
placeholder="Hover here..."
innerRef={x => { this.input = x }}
onMouseEnter={() => this.input.focus()}
/>
);
}
}
render(
<Form />
);
\`\`\`
`
export default Refs
|
import md from 'components/md'
const Refs = () => md`
## Refs
Passing a \`ref\` prop to a styled component will give you an instance of
the \`StyledComponent\` wrapper, but not to the underlying DOM node.
This is due to how refs work.
It's not possible to call DOM methods, like \`focus\`, on our wrappers directly.
To get a ref to the actual, wrapped DOM node, pass the callback to the \`innerRef\` prop instead.
> We don't support string refs (i.e. \`innerRef="node"\`), since they're already deprecated in React.
This example uses \`innerRef\` to save a ref to the styled input and focuses it once the user
hovers over it.
\`\`\`react
const Input = styled.input\`
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
\`;
class Form extends React.Component {
render() {
return (
<Input
placeholder="Hover here..."
innerRef={x => this.input = x}
onMouseEnter={() => this.input.focus()}
/>
);
}
}
render(
<Form />
);
\`\`\`
`
export default Refs
|
Fix wording for mapping follow tooltips
|
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
return [
'comment' => [
'empty' => 'No comments watched.',
'page_title' => 'comment watchlist',
'title' => 'comment',
'table' => [
'latest_comment_empty' => 'no comments',
'latest_comment_value' => ':time by :username',
],
],
'forum_topic' => [
'title' => 'forum topic',
],
'index' => [
'title_compact' => 'watchlists',
],
'mapping' => [
'empty' => 'No mappers watched.',
'followers' => 'mapping subscribers',
'page_title' => 'mapper watchlist',
'title' => 'mapper',
'to_0' => 'stop notifying me when this user uploads new beatmaps',
'to_1' => 'notify me when this user uploads new beatmaps',
],
'modding' => [
'title' => 'beatmap discussion',
],
];
|
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
return [
'comment' => [
'empty' => 'No comments watched.',
'page_title' => 'comment watchlist',
'title' => 'comment',
'table' => [
'latest_comment_empty' => 'no comments',
'latest_comment_value' => ':time by :username',
],
],
'forum_topic' => [
'title' => 'forum topic',
],
'index' => [
'title_compact' => 'watchlists',
],
'mapping' => [
'empty' => 'No mappers watched.',
'followers' => 'mapping subscribers',
'page_title' => 'mapper watchlist',
'title' => 'mapper',
'to_0' => 'stop notifying me when this user uploads new beatmap',
'to_1' => 'notify me when this user uploads new beatmap',
],
'modding' => [
'title' => 'beatmap discussion',
],
];
|
Add scene items for hamburger menu
|
import React, { Component } from 'react'
import { Scene, Router } from 'react-native-router-flux'
import Styles from './Styles/NavigationContainerStyle'
import NavigationDrawer from './NavigationDrawer'
import NavItems from './NavItems'
import CustomNavBar from '../Components/CustomNavBar'
// Screens Identified By The Router
import PresentationScreen from '../Containers/PresentationScreen'
import LoginScreen from '../Containers/LoginScreen'
import DeviceInfoScreen from '../Containers/DeviceInfoScreen'
import TravContainer from '../Containers/TravContainer'
// Documentation: https://github.com/aksonov/react-native-router-flux
class NavigationRouter extends Component {
render () {
return (
<Router>
<Scene key='drawer' component={NavigationDrawer} open={false}>
<Scene key='drawerChildrenWrapper' navigationBarStyle={Styles.navBar} titleStyle={Styles.title} leftButtonIconStyle={Styles.leftButton} rightButtonTextStyle={Styles.rightButton}>
<Scene initial key='presentationScreen' component={TravContainer} title='Traveller' renderLeftButton={NavItems.hamburgerButton} />
<Scene key='travContainer' component={TravContainer} title='Traveller' />
<Scene key='deviceInfo' component={DeviceInfoScreen} title='Device Info' navBar={CustomNavBar} />
</Scene>
</Scene>
</Router>
)
}
}
export default NavigationRouter
|
import React, { Component } from 'react'
import { Scene, Router } from 'react-native-router-flux'
import Styles from './Styles/NavigationContainerStyle'
import NavigationDrawer from './NavigationDrawer'
import NavItems from './NavItems'
import CustomNavBar from '../Components/CustomNavBar'
// Screens Identified By The Router
import PresentationScreen from '../Containers/PresentationScreen'
import LoginScreen from '../Containers/LoginScreen'
import DeviceInfoScreen from '../Containers/DeviceInfoScreen'
import TravContainer from '../Containers/TravContainer'
// Documentation: https://github.com/aksonov/react-native-router-flux
class NavigationRouter extends Component {
render () {
return (
<Router>
<Scene key='drawer' component={NavigationDrawer} open={false}>
<Scene key='drawerChildrenWrapper' navigationBarStyle={Styles.navBar} titleStyle={Styles.title} leftButtonIconStyle={Styles.leftButton} rightButtonTextStyle={Styles.rightButton}>
<Scene initial key='presentationScreen' component={TravContainer} title='Traveller' renderLeftButton={NavItems.hamburgerButton} />
</Scene>
</Scene>
</Router>
)
}
}
export default NavigationRouter
|
Bump version number for release.
|
from setuptools import setup
import io
import os
version = '0.2.5'
readme_path = os.path.join(os.path.dirname(__file__), 'README.rst')
with io.open(readme_path, encoding='utf-8') as f:
long_description = f.read()
setup(
name='markdown2ctags',
description='Generates ctags-compatible output for the sections of a '
'Markdown document.',
long_description=long_description,
license='BSD',
author='John Szakmeister',
author_email='john@szakmeister.net',
url='https://github.com/jszakmeister/markdown2ctags',
version=version,
py_modules=['markdown2ctags'],
zip_safe=True,
entry_points={
'console_scripts': [
'markdown2ctags = markdown2ctags:cli_main',
],
},
classifiers=[
'License :: OSI Approved :: BSD License',
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development',
'Topic :: Text Processing',
'Topic :: Text Processing :: Indexing',
'Topic :: Utilities',
]
)
|
from setuptools import setup
import io
import os
version = '0.2.4'
readme_path = os.path.join(os.path.dirname(__file__), 'README.rst')
with io.open(readme_path, encoding='utf-8') as f:
long_description = f.read()
setup(
name='markdown2ctags',
description='Generates ctags-compatible output for the sections of a '
'Markdown document.',
long_description=long_description,
license='BSD',
author='John Szakmeister',
author_email='john@szakmeister.net',
url='https://github.com/jszakmeister/markdown2ctags',
version=version,
py_modules=['markdown2ctags'],
zip_safe=True,
entry_points={
'console_scripts': [
'markdown2ctags = markdown2ctags:cli_main',
],
},
classifiers=[
'License :: OSI Approved :: BSD License',
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Software Development',
'Topic :: Text Processing',
'Topic :: Text Processing :: Indexing',
'Topic :: Utilities',
]
)
|
Handle exec-sync failure on Windows.
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
environment: environment,
baseURL: '/',
locationType: 'hash',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
var hash = '(unknown git revision)';
try {
var execSync = require('exec-sync');
var gitStatus = execSync('git describe --long --abbrev=10 --all --always --dirty');
var parts = gitStatus.split('-');
var hash = parts[parts.length-1];
if (parts[parts.length-1] == 'dirty') {
hash = parts[parts.length-2] + '-dirty';
}
} catch(error) {
console.error('exec-sync: git describe failed', error);
}
ENV.APP.version = require('../package.json').version + ' (' + hash + ')';
if (environment === 'development') {
ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
ENV.APP.LOG_MODULE_RESOLVER = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'production') {
}
return ENV;
};
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
environment: environment,
baseURL: '/',
locationType: 'hash',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
var execSync = require('exec-sync');
var gitStatus = execSync('git describe --long --abbrev=10 --all --always --dirty');
var parts = gitStatus.split('-');
var hash = parts[parts.length-1];
if (parts[parts.length-1] == 'dirty') {
hash = parts[parts.length-2] + '-dirty';
}
ENV.APP.version = require('../package.json').version + ' (' + hash + ')';
if (environment === 'development') {
ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
ENV.APP.LOG_MODULE_RESOLVER = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'production') {
}
return ENV;
};
|
Fix import error by calling prepare_env first
|
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
import logging
from awx import __version__ as tower_version
# Prepare the AWX environment.
from awx import prepare_env
prepare_env()
from django.core.wsgi import get_wsgi_application
"""
WSGI config for AWX project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
logger = logging.getLogger('awx.main.models.jobs')
try:
fd = open("/var/lib/awx/.tower_version", "r")
if fd.read().strip() != tower_version:
raise Exception()
except Exception:
logger.error("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.")
raise Exception("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.")
# Return the default Django WSGI application.
application = get_wsgi_application()
|
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.
import logging
from django.core.wsgi import get_wsgi_application
from awx import prepare_env
from awx import __version__ as tower_version
"""
WSGI config for AWX project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
# Prepare the AWX environment.
prepare_env()
logger = logging.getLogger('awx.main.models.jobs')
try:
fd = open("/var/lib/awx/.tower_version", "r")
if fd.read().strip() != tower_version:
raise Exception()
except Exception:
logger.error("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.")
raise Exception("Missing or incorrect metadata for Tower version. Ensure Tower was installed using the setup playbook.")
# Return the default Django WSGI application.
application = get_wsgi_application()
|
Fix error handling and call order
|
module.exports = Backbone.View.extend({
className: 'main_price main_wrap',
initialize: function(){
var self = this
self.$el.html(ss.tmpl['main-pairing'].render()).appendTo('.dash .main').addClass('animated fadeInUp')
self.display_qr();
},
clear: function(){
var self = this
self.$el.removeClass('animated fadeInUp')
self.$el.addClass('animatedQuick fadeOutUp')
setTimeout(function(){
self.$el.remove()
}, 500)
},
display_qr: function(){
var self = this
self.user.get_server_address(function(err, address){
if (err) return alert('Getting server address failed: ' + err.message)
self.user.create_pairing_token(function(err_, token){
if (err_) return alert('Pairing failed: ' + err_.message)
new QRCode(document.getElementById('qrcode'), JSON.stringify({
token: token,
trader: address
}))
})
})
}
})
|
module.exports = Backbone.View.extend({
className: 'main_price main_wrap',
initialize: function(){
var self = this
self.$el.html(ss.tmpl['main-pairing'].render()).appendTo('.dash .main').addClass('animated fadeInUp')
self.display_qr();
},
clear: function(){
var self = this
self.$el.removeClass('animated fadeInUp')
self.$el.addClass('animatedQuick fadeOutUp')
setTimeout(function(){
self.$el.remove()
}, 500)
},
display_qr: function(){
var self = this
self.user.create_pairing_token(function(err, token){
if (err) return alert('Pairing failed: ' + err.message)
self.user.get_server_address(function(err, address){
new QRCode(document.getElementById('qrcode'), JSON.stringify({
token: token,
trader: address
}))
})
})
}
})
|
Use constants for component/validator types in cloud tenant form
|
import { componentTypes, validatorTypes } from '@@ddf';
/**
* @param {Boolean} renderEmsChoices
* @param {Object} emsChoices
*/
function createSchema(renderEmsChoices, emsChoices) {
let fields = [{
component: componentTypes.TEXT_FIELD,
name: 'name',
validate: [{
type: validatorTypes.REQUIRED,
}],
label: __('Tenant Name'),
maxLength: 128,
validateOnMount: true,
}];
if (!renderEmsChoices) {
fields = [{
component: componentTypes.SELECT,
name: 'ems_id',
menuPlacement: 'bottom',
label: __('Cloud Provider/Parent Cloud Tenant'),
placeholder: `<${__('Choose')}>`,
validateOnMount: true,
validate: [{
type: validatorTypes.REQUIRED,
}],
options: Object.keys(emsChoices).map(key => ({
value: emsChoices[key],
label: key,
})),
}, ...fields];
}
return { fields };
}
export default createSchema;
|
/**
* @param {Boolean} renderEmsChoices
* @param {Object} emsChoices
*/
function createSchema(renderEmsChoices, emsChoices) {
let fields = [{
component: 'text-field',
name: 'name',
validate: [{
type: 'required-validator',
}],
label: __('Tenant Name'),
maxLength: 128,
validateOnMount: true,
}];
if (!renderEmsChoices) {
fields = [{
component: 'select-field',
name: 'ems_id',
menuPlacement: 'bottom',
label: __('Cloud Provider/Parent Cloud Tenant'),
placeholder: `<${__('Choose')}>`,
validateOnMount: true,
validate: [{
type: 'required-validator',
}],
options: Object.keys(emsChoices).map(key => ({
value: emsChoices[key],
label: key,
})),
}, ...fields];
}
return { fields };
}
export default createSchema;
|
Sort the reducers to improve everybodys life
|
import { AppRoute } from './app';
import overview from './overview';
import events from './events';
import company from './company';
import users from './users';
import articles from './articles';
import meetings from './meetings';
import admin from './admin';
import quotes from './quotes';
import podcasts from './podcasts';
import photos from './photos';
import pages from './pages';
import search from './search';
import interestGroups from './interestgroups';
import joblistings from './joblistings';
import pageNotFound from './pageNotFound';
import announcements from './announcements';
import companyInterest from './companyInterest';
import bdb from './bdb';
import contact from './contact';
import timeline from './timeline';
import surveys from './surveys';
import tags from './tags';
export default {
path: '/',
component: AppRoute,
indexRoute: overview,
childRoutes: [
events,
users,
articles,
photos,
meetings,
admin,
quotes,
podcasts,
pages,
company,
search,
interestGroups,
joblistings,
announcements,
bdb,
contact,
timeline,
...companyInterest,
surveys,
tags,
pageNotFound
]
};
|
import { AppRoute } from './app';
import overview from './overview';
import events from './events';
import company from './company';
import users from './users';
import articles from './articles';
import meetings from './meetings';
import admin from './admin';
import quotes from './quotes';
import photos from './photos';
import pages from './pages';
import search from './search';
import interestGroups from './interestgroups';
import joblistings from './joblistings';
import pageNotFound from './pageNotFound';
import announcements from './announcements';
import companyInterest from './companyInterest';
import bdb from './bdb';
import contact from './contact';
import timeline from './timeline';
import surveys from './surveys';
import tags from './tags';
export default {
path: '/',
component: AppRoute,
indexRoute: overview,
childRoutes: [
events,
users,
articles,
photos,
meetings,
admin,
quotes,
pages,
company,
search,
interestGroups,
joblistings,
announcements,
bdb,
contact,
timeline,
...companyInterest,
surveys,
tags,
pageNotFound
]
};
|
Migrate script now also updates CropTemplate
|
<?php
class Garp_Cli_Command_Models extends Garp_Cli_Command {
/**
* Garp models have moved from the G_Model namespace to the Garp_Model_Db_ namespace.
* This command migrates extended models to the new namespace.
*/
public function migrateGarpModels() {
$modelDir = APPLICATION_PATH . '/modules/default/Model';
$dirIterator = new DirectoryIterator($modelDir);
foreach ($dirIterator as $finfo) {
if ($finfo->isDot()) {
continue;
}
$this->_modifyModelFile($finfo);
}
$this->_updateCropTemplateRefs();
}
// Change references to G_Model_CropTemplate
protected function _updateCropTemplateRefs() {
$iniPaths = ['/configs/content.ini', '/configs/acl.ini'];
foreach ($iniPaths as $i => $path) {
$content = file_get_contents(APPLICATION_PATH . $path);
$content = str_replace('G_Model_CropTemplate', 'Garp_Model_Db_CropTemplate', $content);
file_put_contents(APPLICATION_PATH . $path, $content);
}
}
protected function _modifyModelFile($finfo) {
$path = $finfo->getPath() . DIRECTORY_SEPARATOR . $finfo->getFilename();
$contents = file_get_contents($path);
if (strpos($contents, 'extends G_Model_') === false) {
return;
}
$contents = str_replace('extends G_Model_', 'extends Garp_Model_Db_', $contents);
return file_put_contents($path, $contents);
}
}
|
<?php
class Garp_Cli_Command_Models extends Garp_Cli_Command {
/**
* Garp models have moved from the G_Model namespace to the Garp_Model_Db_ namespace.
* This command migrates extended models to the new namespace.
*/
public function migrateGarpModels() {
$modelDir = APPLICATION_PATH . '/modules/default/Model';
$dirIterator = new DirectoryIterator($modelDir);
foreach ($dirIterator as $finfo) {
if ($finfo->isDot()) {
continue;
}
$this->_modifyModelFile($finfo);
}
}
protected function _modifyModelFile($finfo) {
$path = $finfo->getPath() . DIRECTORY_SEPARATOR . $finfo->getFilename();
$contents = file_get_contents($path);
if (strpos($contents, 'extends G_Model_') === false) {
return;
}
$contents = str_replace('extends G_Model_', 'extends Garp_Model_Db_', $contents);
return file_put_contents($path, $contents);
}
}
|
Make the multithreaded coinitialize only on 64bit
Change-Id: I5d44efb634051f00cd3ca54b99ce0dea806543be
|
# Copyright 2012 Cloudbase Solutions Srl
#
# 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.
import struct
import sys
if struct.calcsize("P") == 8 and sys.platform == 'win32':
# This is needed by Nano Server.
# Set COINIT_MULTITHREADED only on x64 interpreters due to issues on x86.
import pythoncom
sys.coinit_flags = pythoncom.COINIT_MULTITHREADED
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
from oslo_config import cfg
from oslo_log import log as oslo_logging
from cloudbaseinit import init
from cloudbaseinit.utils import log as logging
CONF = cfg.CONF
LOG = oslo_logging.getLogger(__name__)
def main():
CONF(sys.argv[1:])
logging.setup('cloudbaseinit')
try:
init.InitManager().configure_host()
except Exception as exc:
LOG.exception(exc)
raise
if __name__ == "__main__":
main()
|
# Copyright 2012 Cloudbase Solutions Srl
#
# 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.
import sys
import pythoncom
sys.coinit_flags = pythoncom.COINIT_MULTITHREADED
pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
from oslo_config import cfg
from oslo_log import log as oslo_logging
from cloudbaseinit import init
from cloudbaseinit.utils import log as logging
CONF = cfg.CONF
LOG = oslo_logging.getLogger(__name__)
def main():
CONF(sys.argv[1:])
logging.setup('cloudbaseinit')
try:
init.InitManager().configure_host()
except Exception as exc:
LOG.exception(exc)
raise
if __name__ == "__main__":
main()
|
Fix reserved keyword override with import
|
"""
A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup
# To use a consistent encoding
from codecs import open as codecopen
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with codecopen(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='paragoo', # pip install paragoo
description='Static site generator',
#long_description=open('README.md', 'rt').read(),
long_description=long_description,
# version
# third part for minor release
# second when api changes
# first when it becomes stable someday
version='0.2.0',
author='Michiel Scholten',
author_email='michiel@diginaut.net',
url='https://github.com/aquatix/paragoo',
license='Apache',
# as a practice no need to hard code version unless you know program wont
# work unless the specific versions are used
install_requires=['Jinja2', 'Markdown', 'MarkupSafe', 'docutils', 'pygments', 'PyYAML', 'click', 'requests', 'bs4','utilkit>=0.3.0'],
py_modules=['paragoo'],
zip_safe=True,
)
|
"""
A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='paragoo', # pip install paragoo
description='Static site generator',
#long_description=open('README.md', 'rt').read(),
long_description=long_description,
# version
# third part for minor release
# second when api changes
# first when it becomes stable someday
version='0.2.0',
author='Michiel Scholten',
author_email='michiel@diginaut.net',
url='https://github.com/aquatix/paragoo',
license='Apache',
# as a practice no need to hard code version unless you know program wont
# work unless the specific versions are used
install_requires=['Jinja2', 'Markdown', 'MarkupSafe', 'docutils', 'pygments', 'PyYAML', 'click', 'requests', 'bs4','utilkit>=0.3.0'],
py_modules=['paragoo'],
zip_safe=True,
)
|
Remove support for python 2.7 in package classifiers
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
from github_backup import __version__
def open_file(fname):
return open(os.path.join(os.path.dirname(__file__), fname))
setup(
name='github-backup',
version=__version__,
author='Jose Diaz-Gonzalez',
author_email='github-backup@josediazgonzalez.com',
packages=['github_backup'],
scripts=['bin/github-backup'],
url='http://github.com/josegonzalez/python-github-backup',
license=open('LICENSE.txt').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Topic :: System :: Archiving :: Backup',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
description='backup a github user or organization',
long_description=open_file('README.rst').read(),
install_requires=open_file('requirements.txt').readlines(),
zip_safe=True,
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
from github_backup import __version__
def open_file(fname):
return open(os.path.join(os.path.dirname(__file__), fname))
setup(
name='github-backup',
version=__version__,
author='Jose Diaz-Gonzalez',
author_email='github-backup@josediazgonzalez.com',
packages=['github_backup'],
scripts=['bin/github-backup'],
url='http://github.com/josegonzalez/python-github-backup',
license=open('LICENSE.txt').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Topic :: System :: Archiving :: Backup',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
description='backup a github user or organization',
long_description=open_file('README.rst').read(),
install_requires=open_file('requirements.txt').readlines(),
zip_safe=True,
)
|
Fix migration 0023 subscriber model reference
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-07 09:37
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
DJSTRIPE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL)
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('djstripe', '0022_fix_subscriber_delete'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='subscriber',
field=models.ForeignKey(null=True, on_delete=models.SET_NULL, related_name='djstripe_customers', to=DJSTRIPE_SUBSCRIBER_MODEL),
),
migrations.AlterUniqueTogether(
name='customer',
unique_together=set([('subscriber', 'livemode')]),
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-07 09:37
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('djstripe', '0022_fix_subscriber_delete'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='subscriber',
field=models.ForeignKey(null=True, on_delete=models.SET_NULL, related_name='djstripe_customers', to=settings.AUTH_USER_MODEL),
),
migrations.AlterUniqueTogether(
name='customer',
unique_together=set([('subscriber', 'livemode')]),
),
]
|
Clean up. Remove what is not used for now.
|
import Keyboard from './keyboard';
import Mouse from './mouse';
import Recorder from './recorder';
const Mimic = (params) => {
const container = document.getElementById(params.container),
recorder = Recorder('session'),
keyboard = Keyboard(),
mouse = Mouse(container);
const startRecording = () => {
recorder.record('Start recording');
keyboard.record();
mouse.record();
}
const stopRecording = () => {
keyboard.stop();
mouse.stop();
recorder.record('Stop recording');
}
const init = () => {
document.getElementById('start').onclick = (e) => {
e.preventDefault();
startRecording();
};
document.getElementById('stop').onclick = (e) => {
e.preventDefault();
stopRecording();
};
}
return {
init
}
}
global.Mimic = Mimic;
|
import config from './config';
import Keyboard from './keyboard';
import Mouse from './mouse';
import Recorder from './recorder';
import Scroll from './scroll';
import Timer from './timer';
import moment from 'moment';
import Data from '../db/eventsLog';
const Mimic = (params) => {
const container = document.getElementById(params.container),
recorder = Recorder('session'),
keyboard = Keyboard(),
mouse = Mouse(container),
scroll = Scroll();
const startRecording = () => {
console.log(Data);
recorder.record('Start recording');
keyboard.record();
mouse.record();
scroll.record();
}
const stopRecording = () => {
keyboard.stop();
mouse.stop();
scroll.stop();
recorder.record('Stop recording');
console.log(Data);
}
const init = () => {
document.getElementById('start').onclick = (e) => {
e.preventDefault();
startRecording();
};
document.getElementById('stop').onclick = (e) => {
e.preventDefault();
stopRecording();
};
}
return {
init
}
}
global.Mimic = Mimic;
|
Add Python 3.6 to classifiers
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='Redis-Sentinel-Url',
py_modules=['redis_sentinel_url'],
version='1.0.0',
install_requires=['redis>=2.10.3'],
tests_require=['mock', 'nose'],
test_suite='nose.collector',
description='A factory for redis connection that supports using Redis Sentinel',
url='https://github.com/exponea/redis-sentinel-url',
author='Martin Sucha',
author_email='martin.sucha@exponea.com',
license='Apache 2.0',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'License :: OSI Approved :: Apache Software License',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='Redis-Sentinel-Url',
py_modules=['redis_sentinel_url'],
version='1.0.0',
install_requires=['redis>=2.10.3'],
tests_require=['mock', 'nose'],
test_suite='nose.collector',
description='A factory for redis connection that supports using Redis Sentinel',
url='https://github.com/exponea/redis-sentinel-url',
author='Martin Sucha',
author_email='martin.sucha@exponea.com',
license='Apache 2.0',
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Operating System :: OS Independent',
'License :: OSI Approved :: Apache Software License',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
Fix build success message color
|
import webpack from 'webpack'
import { log } from '../util/log'
export default function buildAndDistribute ({ webpackConfig, watch }) {
const compiler = webpack(webpackConfig)
compiler.run((err, stats) => {
var softErrors = !err && stats.toJson().errors
var hasSoftErrors = softErrors && softErrors.length > 0
if (err) {
console.error(err.stack || err)
if (err.details) console.error(err.details)
}
if (hasSoftErrors) {
softErrors.forEach(function (error) {
console.error(error)
})
}
if (!watch && (err || hasSoftErrors)) {
process.on('exit', function () {
process.exit(1)
})
return
}
log('Build complete, files written in the dist/ folder.')
})
}
|
import webpack from 'webpack'
import { logError } from '../util/log'
export default function buildAndDistribute ({ webpackConfig, watch }) {
const compiler = webpack(webpackConfig)
compiler.run((err, stats) => {
var softErrors = !err && stats.toJson().errors
var hasSoftErrors = softErrors && softErrors.length > 0
if (err) {
console.error(err.stack || err)
if (err.details) console.error(err.details)
}
if (hasSoftErrors) {
softErrors.forEach(function (error) {
console.error(error)
})
}
if (!watch && (err || hasSoftErrors)) {
process.on('exit', function () {
process.exit(1)
})
return
}
logError('Build complete, files written in the dist/ folder.')
})
}
|
Improve code style on test arc proxy
|
package pt.fccn.arquivo.tests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import pt.fccn.arquivo.pages.Arcproxyinspection;
import pt.fccn.arquivo.pages.IndexPage;
import pt.fccn.saw.selenium.WebDriverTestBaseParalell;
import pt.fccn.saw.selenium.Retry;
public class TestArcproxy extends WebDriverTestBaseParalell {
public TestArcproxy(String os, String version, String browser, String deviceName, String deviceOrientation) {
super(os, version, browser, deviceName, deviceOrientation);
}
@Test
@Retry
public void testArcproxy() {
IndexPage index = new IndexPage(driver);
Arcproxyinspection arcproxy = index.arcProxy(isPreProd);
assertTrue("There are problems in the coherence of ArcProxy ", arcproxy.inspectArcproxy(false));
assertTrue("The date of archived pages are not the same before perfomed ", arcproxy.inspectArcproxy(true));
}
}
|
package pt.fccn.arquivo.tests;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import pt.fccn.arquivo.pages.Arcproxyinspection;
import pt.fccn.arquivo.pages.IndexPage;
import pt.fccn.saw.selenium.WebDriverTestBaseParalell;
import pt.fccn.saw.selenium.Retry;
/**
* @author nutchwax
*
*/
public class TestArcproxy extends WebDriverTestBaseParalell{
public TestArcproxy(String os, String version, String browser, String deviceName, String deviceOrientation) {
super(os, version, browser, deviceName, deviceOrientation);
}
@Test
@Retry
public void TestArcproxy() {
System.out.print("Running TestArcproxy. \n");
IndexPage index = new IndexPage(driver);
Arcproxyinspection arcproxy = index.arcProxy(isPreProd);
try {
assertTrue("There are problems in the coherence of ArcProxy ",arcproxy.inspectArcproxy(false));
assertTrue("The date of archived pages are not the same before perfomed ",arcproxy.inspectArcproxy(true));
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Set getAssetPath method stub in render function used in tests
|
const nunjucks = require('nunjucks')
const jsdom = require('jsdom')
const { JSDOM } = jsdom
const tradeElementsFilters = require('~/config/nunjucks/trade-elements-filters')
const dataHubFilters = require('~/config/nunjucks/filters')
const filters = Object.assign({}, tradeElementsFilters, dataHubFilters)
nunjucks.configure('views')
const nunenv = nunjucks.configure([
`${rootPath}/src/views`,
], {
autoescape: true,
})
Object.keys(filters).forEach((filterName) => {
nunenv.addFilter(filterName, filters[filterName])
})
function render (template, options) {
options.getAssetPath = () => {} // Stub method set in middleware locals
return new Promise((resolve, reject) => {
try {
const markup = nunjucks.render(template, options)
const { document } = (new JSDOM(markup).window)
resolve(document)
} catch (error) {
console.log(error)
reject(error)
}
})
}
module.exports = { render }
|
const nunjucks = require('nunjucks')
const jsdom = require('jsdom')
const { JSDOM } = jsdom
const tradeElementsFilters = require('~/config/nunjucks/trade-elements-filters')
const dataHubFilters = require('~/config/nunjucks/filters')
const filters = Object.assign({}, tradeElementsFilters, dataHubFilters)
nunjucks.configure('views')
const nunenv = nunjucks.configure([
`${rootPath}/src/views`,
], {
autoescape: true,
})
Object.keys(filters).forEach((filterName) => {
nunenv.addFilter(filterName, filters[filterName])
})
nunenv.addGlobal('getAssetPath', () => {})
function render (template, options) {
return new Promise((resolve, reject) => {
try {
const markup = nunjucks.render(template, options)
const { document } = (new JSDOM(markup).window)
resolve(document)
} catch (error) {
console.log(error)
reject(error)
}
})
}
module.exports = { render }
|
Allow no tag to be set
|
<?php
/**
* Class GACodeField
*/
class GACodeField extends TextField
{
/**
* @return string
*/
public function Type()
{
return 'text';
}
/**
* Simple validation to make sure the input matches the expected pattern.
*
* @param $validator
* @return bool
*/
public function validate($validator)
{
if (is_null($this->value)) {
return true;
} else {
$parts = explode("-", $this->value);
}
if ($parts[0] === "GTM" && mb_strlen($parts[1]) === 6) {
return true;
} else if (($parts[0] === "UA") && mb_strlen($parts[1]) === 8 && mb_strlen($parts[2]) === 1) {
return true;
} else {
$validator->validationError($this->name, "<strong>ERROR:</strong> Isn't a valid Universal or Tag Manager code. Must be in either <strong>UA-XXXXXXXX-X</strong> or
<strong>GTM-XXXXXX</strong> format.", "validation", false);
}
return false;
}
}
|
<?php
/**
* Class GACodeField
*/
class GACodeField extends TextField
{
/**
* @return string
*/
public function Type()
{
return 'text';
}
/**
* Simple validation to make sure the input matches the expected pattern.
*
* @param $validator
* @return bool
*/
public function validate($validator)
{
$parts = explode("-", $this->value);
if ($parts[0] === "GTM" && mb_strlen($parts[1]) === 6) {
return true;
} else if (($parts[0] === "UA") && mb_strlen($parts[1]) === 8 && mb_strlen($parts[2]) === 1) {
return true;
} else {
$validator->validationError($this->name, "<strong>ERROR:</strong> Isn't a valid Universal or Tag Manager code. Must be in either <strong>UA-XXXXXXXX-X</strong> or
<strong>GTM-XXXXXX</strong> format.", "validation", false);
}
return false;
}
}
|
Add location scope to Google Fit
|
/*
* Copyright 2017 Open mHealth
*
* 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 org.openmhealth.shim.googlefit;
import org.openmhealth.shim.OAuth2ClientSettings;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* @author Emerson Farrugia
*/
@Component
@ConfigurationProperties("openmhealth.shim.googlefit")
public class GoogleFitClientSettings extends OAuth2ClientSettings {
private List<String> scopes = Arrays.asList(
"https://www.googleapis.com/auth/fitness.activity.read",
"https://www.googleapis.com/auth/fitness.body.read",
"https://www.googleapis.com/auth/fitness.location.read"
);
@Override
public List<String> getScopes() {
return scopes;
}
public void setScopes(List<String> scopes) {
this.scopes = scopes;
}
}
|
/*
* Copyright 2017 Open mHealth
*
* 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 org.openmhealth.shim.googlefit;
import org.openmhealth.shim.OAuth2ClientSettings;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
* @author Emerson Farrugia
*/
@Component
@ConfigurationProperties("openmhealth.shim.googlefit")
public class GoogleFitClientSettings extends OAuth2ClientSettings {
private List<String> scopes = Arrays.asList(
"https://www.googleapis.com/auth/fitness.activity.read",
"https://www.googleapis.com/auth/fitness.body.read"
);
@Override
public List<String> getScopes() {
return scopes;
}
public void setScopes(List<String> scopes) {
this.scopes = scopes;
}
}
|
Add more data to the report
|
var uuid = require('node-uuid');
var JSData = require('js-data');
var store;
var adapter;
var Report;
function error(msg) {
return new Promise(function(resolve, reject) {
return resolve({ error: msg });
});
}
function get(id) {
if (!id) return error('No id specified.');
if (!adapter) {
return new Promise(function(resolve) {
var report = Report.get(id);
return resolve(report);
});
}
return Report.find(id);
}
function add(data) {
if (!data.type || !data.payload) {
return error('Required parameters aren\'t specified.');
}
var obj = {
id: uuid.v4(),
type: data.type,
title: data.title,
description: data.description,
failed: data.failed,
payload: data.payload,
screen: data.screen,
user: data.user,
isLog: !!data.isLog,
added: Date.now()
};
if (!adapter) {
return new Promise(function(resolve) {
var report = Report.inject(obj);
return resolve(report);
});
}
return Report.create(obj);
}
function createStore(options) {
store = new JSData.DS();
Report = store.defineResource('report');
return {
get: get,
add: add
};
}
module.exports = createStore;
|
var uuid = require('node-uuid');
var JSData = require('js-data');
var store;
var adapter;
var Report;
function error(msg) {
return new Promise(function(resolve, reject) {
return resolve({ error: msg });
});
}
function get(id) {
if (!id) return error('No id specified.');
if (!adapter) {
return new Promise(function(resolve) {
var report = Report.get(id);
return resolve(report);
});
}
return Report.find(id);
}
function add(data) {
if (!data.type || !data.payload) {
return error('Required parameters aren\'t specified.');
}
var obj = {
id: uuid.v4(),
type: data.type,
payload: data.payload
};
if (!adapter) {
return new Promise(function(resolve) {
var report = Report.inject(obj);
return resolve(report);
});
}
return Report.create(obj);
}
function createStore(options) {
store = new JSData.DS();
Report = store.defineResource('report');
return {
get: get,
add: add
};
}
module.exports = createStore;
|
Set email address as optional to show optional label
|
const { isEmpty, pickBy } = require('lodash')
const logger = require('../../../config/logger')
const { createZenDeskMessage, postToZenDesk } = require('./services')
async function postFeedback (req, res, next) {
const { title, feedbackType, email } = req.body
const messages = pickBy({
title: !title && 'Your feedback needs a title',
feedbackType: !feedbackType && 'You need to choose between raising a problem and leaving feedback',
email: (!email.match(/.*@.*\..*/)) && 'A valid email address is required',
})
res.locals.formErrors = Object.assign({}, res.locals.formErrors, {
messages,
})
const hasErrors = !isEmpty(res.locals.formErrors.messages) || res.locals.formErrors.summary
if (hasErrors) {
return next()
}
const ticket = createZenDeskMessage(req.body)
try {
const response = await postToZenDesk(ticket)
// TODO: Look into improving confirmation page https://www.gov.uk/service-manual/design/confirmation-pages
req.flash('success', `Created new report, reference number ${response.data.ticket.id}`)
res.redirect('/support/thank-you')
} catch (error) {
logger.error(error)
res.locals.formErrors = {
summary: error.message,
}
next()
}
}
module.exports = {
postFeedback,
}
|
const { isEmpty, pickBy } = require('lodash')
const logger = require('../../../config/logger')
const { createZenDeskMessage, postToZenDesk } = require('./services')
async function postFeedback (req, res, next) {
const { title, feedbackType, email } = req.body
const messages = pickBy({
title: !title && 'Your feedback needs a title',
feedbackType: !feedbackType && 'You need to choose between raising a problem and leaving feedback',
email: (email && !email.match(/.*@.*\..*/)) && 'A valid email address is required',
})
res.locals.formErrors = Object.assign({}, res.locals.formErrors, {
messages,
})
const hasErrors = !isEmpty(res.locals.formErrors.messages) || res.locals.formErrors.summary
if (hasErrors) {
return next()
}
const ticket = createZenDeskMessage(req.body)
try {
const response = await postToZenDesk(ticket)
// TODO: Look into improving confirmation page https://www.gov.uk/service-manual/design/confirmation-pages
req.flash('success', `Created new report, reference number ${response.data.ticket.id}`)
res.redirect('/support/thank-you')
} catch (error) {
logger.error(error)
res.locals.formErrors = {
summary: error.message,
}
next()
}
}
module.exports = {
postFeedback,
}
|
Remove obsolete variable from tokenize
|
const EXPR = /{([\s\S]+?)}/g;
const BLOCK_START = 'block:';
const BLOCK_END = '/block:';
//const BLOCK_START_EXPR = /{block:([\s\S]+?)}/g;
//const BLOCK_END_EXPR = /{\/block:([\s\S]+?)}/g;
export default class Parser {
constructor() {}
// Tokenizes a raw Tumblr template
// Returns a list of tokens
tokenize(template) {
let tokens = [],
lastIndex = 0,
match;
while ((match = EXPR.exec(template)) !== null) {
if (match.index !== lastIndex) {
tokens.push({type: 'text', value: template.slice(lastIndex, match.index)});
}
lastIndex = EXPR.lastIndex;
if (match[1].startsWith(BLOCK_START)) {
tokens.push({type: 'blockStart', value: match[1].slice(BLOCK_START.length)});
} else if (match[1].startsWith(BLOCK_END)) {
tokens.push({type: 'blockEnd', value: match[1].slice(BLOCK_END.length)});
} else {
tokens.push({type: 'var', value: match[1]});
}
}
return tokens;
}
// Parses a raw Tumblr template
// Returns an AST
parse(template) {
}
}
|
const EXPR = /{([\s\S]+?)}/g;
const BLOCK_START = 'block:';
const BLOCK_END = '/block:';
//const BLOCK_START_EXPR = /{block:([\s\S]+?)}/g;
//const BLOCK_END_EXPR = /{\/block:([\s\S]+?)}/g;
export default class Parser {
constructor() {}
// Tokenizes a raw Tumblr template
// Returns a list of tokens
tokenize(template) {
let tokens = [],
lastIndex = 0,
match, token;
while ((match = EXPR.exec(template)) !== null) {
if (match.index !== lastIndex) {
tokens.push({type: 'text', value: template.slice(lastIndex, match.index)});
}
lastIndex = EXPR.lastIndex;
if (match[1].startsWith(BLOCK_START)) {
tokens.push({type: 'blockStart', value: match[1].slice(BLOCK_START.length)});
} else if (match[1].startsWith(BLOCK_END)) {
tokens.push({type: 'blockEnd', value: match[1].slice(BLOCK_END.length)});
} else {
tokens.push({type: 'var', value: match[1]});
}
}
return tokens;
}
// Parses a raw Tumblr template
// Returns an AST
parse(template) {
}
}
|
Fix documentation for plugin state
|
package com.adaptc.mws.plugins;
/**
* Represents the current state of a plugin.
* @author bsaville
*/
public enum PluginState {
/**
* The plugin is created and ready for use, but is not
* currently receiving any events
*/
STOPPED("Stopped"),
/**
* The plugin is currently receiving events and is working
* correctly.
*/
STARTED("Started"),
/**
* The plugin is currently not receiving any events but is
* also not stopped.
* <p/>
* This should be used when polling or other events should
* stop only temporarily without firing the stop events.
*/
PAUSED("Paused"),
/**
* MWS has detected an error with the plugin and has automatically
* stopped it. Errors could be due to the following reasons:<br>
* <ol>
* <li>An invalid configuration was detected when running the
* {@link AbstractPlugin#configure} method.</li>
* <li>An unexpected exception was thrown during an event, such
* as during polling.</li>
* </ol>
*/
ERRORED("Errored");
private String str;
private PluginState(String str) {
this.str = str;
}
/**
* Returns a human-readable string of the state, such as "Paused" for {@link #PAUSED}.
* @return A human-readable string
*/
@Override
public String toString() {
return str;
}
}
|
package com.adaptc.mws.plugins;
/**
* Represents the current state of a plugin.
* @author bsaville
*/
public enum PluginState {
/**
* The plugin is created and ready for use, but is not
* currently receiving any events
*/
STOPPED("Stopped"),
/**
* The plugin is currently receiving events and is working
* correctly.
*/
STARTED("Started"),
/**
* The plugin is currently not receiving any events but is
* also not stopped.
* <p/>
* This should be used when polling or other events should
* stop only temporarily without firing the stop events.
*/
PAUSED("Paused"),
/**
* MWS has detected an error with the plugin and has automatically
* stopped it. Errors could be due to the following reasons:<br>
* <ol>
* <li>An invalid configuration was detected when running the
* {@link AbstractPlugin#configure} method.
* <li>An unexpected exception was thrown during an event, such
* as during polling.
* </ol>
*/
ERRORED("Errored");
private String str;
private PluginState(String str) {
this.str = str;
}
/**
* Returns a human-readable string of the state, such as "Paused" for {@link #PAUSED}.
* @return A human-readable string
*/
@Override
public String toString() {
return str;
}
}
|
Add BSD license as well
|
from setuptools import setup
setup(
name='django-kewl',
version=".".join(map(str, __import__('short_url').__version__)),
packages=['django_kewl'],
url='https://github.com/Alir3z4/django-kewl',
license='BSD',
author='Alireza Savand',
author_email='alireza.savand@gmail.com',
description='Set of Django kewl utilities & helpers & highly used/needed stuff.',
long_description=open('README.rst').read(),
platforms='OS Independent',
platforms='OS Independent',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Framework :: Django',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development',
'License :: OSI Approved :: BSD License',
],
)
|
from setuptools import setup
setup(
name='django-kewl',
version=".".join(map(str, __import__('short_url').__version__)),
packages=['django_kewl'],
url='https://github.com/Alir3z4/django-kewl',
license='BSD',
author='Alireza Savand',
author_email='alireza.savand@gmail.com',
description='Set of Django kewl utilities & helpers & highly used/needed stuff.',
long_description=open('README.rst').read(),
platforms='OS Independent',
platforms='OS Independent',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Framework :: Django',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development'
],
)
|
Disable source maps for now
|
var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var handleErrors = require('../lib/handleErrors');
var sassConfig = require('../config').sass;
var sasslint = require('gulp-scss-lint');
var gulpFilter = require('gulp-filter');
var base64 = require('gulp-base64');
var classPrefix = require('gulp-class-prefix');
var autoprefixer = require('gulp-autoprefixer');
gulp.task('sass', function() {
var lintFilter = gulpFilter(
['**/*.scss', '!base/**/*', '!vendor/**/*'], {restore: true}
);
return gulp.src(sassConfig.src)
.pipe(sourcemaps.init())
.pipe(lintFilter)
.pipe(sasslint({
'config': 'scss-lint.yml'
}))
.pipe(lintFilter.restore)
.pipe(sass())
.on('error', handleErrors)
.pipe(autoprefixer({
browsers: ['> 1%', 'ie 9']
}))
.on('error', handleErrors)
.pipe(classPrefix('elzar-'))
// .pipe(sourcemaps.write())
.pipe(base64({
extensions: ['svg'],
baseDir: './src'
}))
.pipe(gulp.dest(sassConfig.dest))
.pipe(browserSync.reload({stream:true}));
});
|
var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var handleErrors = require('../lib/handleErrors');
var sassConfig = require('../config').sass;
var sasslint = require('gulp-scss-lint');
var gulpFilter = require('gulp-filter');
var base64 = require('gulp-base64');
var classPrefix = require('gulp-class-prefix');
var autoprefixer = require('gulp-autoprefixer');
gulp.task('sass', function() {
var lintFilter = gulpFilter(
['**/*.scss', '!base/**/*', '!vendor/**/*'], {restore: true}
);
return gulp.src(sassConfig.src)
.pipe(sourcemaps.init())
.pipe(lintFilter)
.pipe(sasslint({
'config': 'scss-lint.yml'
}))
.pipe(lintFilter.restore)
.pipe(sass())
.on('error', handleErrors)
.pipe(autoprefixer({
browsers: ['> 1%', 'ie 9']
}))
.on('error', handleErrors)
.pipe(classPrefix('elzar-'))
.pipe(sourcemaps.write())
.pipe(base64({
extensions: ['svg'],
baseDir: './src'
}))
.pipe(gulp.dest(sassConfig.dest))
.pipe(browserSync.reload({stream:true}));
});
|
Rewrite preparations list test to get ID from URL
|
from django.test import TestCase
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class ListPreparationTestCase(TestCase):
fixtures = ['test_fixtures']
def test_url_endpoint(self):
url = reverse('entry-list-preparations')
self.assertEqual(url, '/entry/preparations')
def test_list_items(self):
"""
Tests to see if the list of preparations
contains the proper preparations
"""
response = self.client.get(reverse('entry-list-preparations'))
items = response.context['item_list']
for preparation in Preparation.objects.all():
self.assertEqual(
items[preparation.id-1]['description'],
preparation.description)
self.assertEqual(
items[preparation.id-1]['name'], preparation.name)
self.assertEqual(
items[preparation.id-1]['link'],
reverse('edit-preparation', kwargs={'id': preparation.id}))
|
from django.test import TestCase
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class ListPreparationTestCase(TestCase):
fixtures = ['test_fixtures']
def test_url_endpoint(self):
url = reverse('entry-list-preparations')
self.assertEqual(url, '/entry/preparations')
def test_list_items(self):
"""
Tests to see if the list of preparations
contains the proper preparations
"""
response = self.client.get(reverse('entry-list-preparations'))
items = response.context['item_list']
for preparation in Preparation.objects.all():
self.assertEqual(
items[preparation.id-1]['description'], preparation.description)
self.assertEqual(
items[preparation.id-1]['name'], preparation.name)
self.assertEqual(
items[preparation.id-1]['link'],
reverse('edit-preparation', kwargs={'id': preparation.id}))
|
style: Change variables to lower case
|
import pyrebase
def initialise(api_key, project_name):
config = {
"apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.initialize_app(config)
def store_url(is_yes, url, user, password, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(user, password)
db = firebase.database()
data = {
"url": url
}
db.child("users").push(data, user['idToken'])
return False
|
import pyrebase
def initialise(FB_API_KEY, project_name):
config = {
"apiKey": FB_API_KEY,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.initialize_app(config)
def store_url(is_yes, url, FB_USER, FB_PASS, firebase):
# do nothing if it's unnecessary
if not is_yes:
return False
# creates token every time maybe worth doing it once every 30m as they
# expire every hour
auth = firebase.auth()
user = auth.sign_in_with_email_and_password(FB_USER, FB_PASS)
db = firebase.database()
data = {
"url": url
}
db.child("users").push(data, user['idToken'])
return False
|
Refactor spec test into two parts, isPingPong and pingPong
|
var pingPong = function(i) {
if (isPingPong) {
if (i % 15 === 0) {
return "pingpong";
} else if (i % 3 === 0) {
return "ping";
} else if (i % 5 === 0) {
return "pong";
}
} else {
return false;
}
}
var isPingPong = function(i) {
if ((i % 5 === 0) || (i % 3 === 0)){
return true;
} else {
return false;
}
}
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
for (var i = 1; i <= number; i += 1) {
if (winner) {
$('#outputList').append("<li>" + winner +"</li>");
} else if (!winner){
$('#outputList').append("<li>" + i +"</li>");
}
}
event.preventDefault();
});
});
|
var pingPong = function(i) {
if ((i % 5 === 0) || (i % 3 === 0)) {
return true;
} else {
return false;
}
};
$(function() {
$("#game").submit(function(event) {
$('#outputList').empty();
var number = parseInt($("#userNumber").val());
for (var i = 1; i <= number; i += 1) {
if (i % 15 === 0) {
$('#outputList').append("<li>ping pong</li>");
} else if (i % 3 === 0) {
$('#outputList').append("<li>ping</li>");
} else if (i % 5 === 0) {
$('#outputList').append("<li>pong</li>");
} else {
$('#outputList').append("<li>" + i + "</li>");
}
}
event.preventDefault();
});
});
|
Update selector to test SVG icon name
|
import Vue from 'vue';
import itemCaretComponent from '~/groups/components/item_caret.vue';
import mountComponent from '../../helpers/vue_mount_component_helper';
const createComponent = (isGroupOpen = false) => {
const Component = Vue.extend(itemCaretComponent);
return mountComponent(Component, {
isGroupOpen,
});
};
describe('ItemCaretComponent', () => {
describe('template', () => {
it('should render component template correctly', () => {
const vm = createComponent();
expect(vm.$el.classList.contains('folder-caret')).toBeTruthy();
expect(vm.$el.querySelectorAll('svg').length).toBe(1);
vm.$destroy();
});
it('should render caret down icon if `isGroupOpen` prop is `true`', () => {
const vm = createComponent(true);
expect(vm.$el.querySelector('svg use').getAttribute('xlink:href')).toContain('angle-down');
vm.$destroy();
});
it('should render caret right icon if `isGroupOpen` prop is `false`', () => {
const vm = createComponent();
expect(vm.$el.querySelector('svg use').getAttribute('xlink:href')).toContain('angle-right');
vm.$destroy();
});
});
});
|
import Vue from 'vue';
import itemCaretComponent from '~/groups/components/item_caret.vue';
import mountComponent from '../../helpers/vue_mount_component_helper';
const createComponent = (isGroupOpen = false) => {
const Component = Vue.extend(itemCaretComponent);
return mountComponent(Component, {
isGroupOpen,
});
};
describe('ItemCaretComponent', () => {
describe('template', () => {
it('should render component template correctly', () => {
const vm = createComponent();
vm.$mount();
expect(vm.$el.classList.contains('folder-caret')).toBeTruthy();
vm.$destroy();
});
it('should render caret down icon if `isGroupOpen` prop is `true`', () => {
const vm = createComponent(true);
vm.$mount();
expect(vm.$el.querySelectorAll('i.fa.fa-caret-down').length).toBe(1);
expect(vm.$el.querySelectorAll('i.fa.fa-caret-right').length).toBe(0);
vm.$destroy();
});
it('should render caret right icon if `isGroupOpen` prop is `false`', () => {
const vm = createComponent();
vm.$mount();
expect(vm.$el.querySelectorAll('i.fa.fa-caret-down').length).toBe(0);
expect(vm.$el.querySelectorAll('i.fa.fa-caret-right').length).toBe(1);
vm.$destroy();
});
});
});
|
Make mysql adapter throw exception if connection cannot be established
|
<?php
namespace Simox\Database\Adapter;
use Simox\Database;
class Mysql extends Database
{
private $db_name;
private $host;
private $username;
private $password;
public function __construct( $params )
{
$this->db_name = $params["db_name"];
$this->host = $params["host"];
$this->username = $params["username"];
$this->password = $params["password"];
}
public function initialize()
{
if ( !isset( $this->db_connection ) )
{
$dsn = "mysql:dbname=" . $this->db_name . ";charset=utf8;host=" . $this->host;
try {
$this->db_connection = new \PDO( $dsn, $this->username, $this->password );
} catch ( \PDOException $e ) {
throw new \Exception( "Access denied." );
}
}
}
}
|
<?php
namespace Simox\Database\Adapter;
use Simox\Database;
class Mysql extends Database
{
private $db_name;
private $host;
private $username;
private $password;
public function __construct( $params )
{
$this->db_name = $params["db_name"];
$this->host = $params["host"];
$this->username = $params["username"];
$this->password = $params["password"];
}
public function initialize()
{
if ( !isset( $this->db_connection ) )
{
$dsn = "mysql:dbname=" . $this->db_name . ";charset=utf8;host=" . $this->host;
$this->db_connection = new \PDO( $dsn, $this->username, $this->password );
}
}
}
|
Create test to check that a person has been added
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
def test_person_added_to_system(self):
initial_person_count = len(self.dojo.all_people)
person = self.dojo.add_person("Neil", "Armstrong", "Staff")
self.assertTrue(person)
new_person_count = len(self.dojo.all_people)
self.assertEqual(new_person_count - initial_person_count, 1)
|
import unittest
from src.dojo import Dojo
class TestCreateRoom (unittest.TestCase):
def test_create_room_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
blue_office = my_class_instance.create_room("office", "Blue")
self.assertTrue(blue_office)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 1)
def test_create_rooms_successfully(self):
my_class_instance = Dojo()
initial_room_count = len(my_class_instance.all_rooms)
offices = my_class_instance.create_room("office", "Blue", "Black", "Brown")
self.assertTrue(offices)
new_room_count = len(my_class_instance.all_rooms)
self.assertEqual(new_room_count - initial_room_count, 3)
|
Include timestamps in log messages
|
# Copyright (c) 2014 Wieland Hoffmann
# License: MIT, see LICENSE for details
import argparse
import logging
from . import config
from .indexing import reindex
logger = logging.getLogger("sir")
def watch(args):
raise NotImplementedError
def main():
loghandler = logging.StreamHandler()
formatter = logging.Formatter(fmt="%(asctime)s %(threadName)s %(levelname)s: %(message)s")
loghandler.setFormatter(formatter)
logger.addHandler(loghandler)
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--debug", action="store_true")
subparsers = parser.add_subparsers()
reindex_parser = subparsers.add_parser("reindex", help="Reindexes all or a single entity type")
reindex_parser.set_defaults(func=reindex)
reindex_parser.add_argument('--entities', action='append', help='The entities to reindex')
watch_parser = subparsers.add_parser("watch", help="Watches for incoming messages on an AMQP queue")
watch_parser.set_defaults(func=watch)
args = parser.parse_args()
if args.debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
config.read_config()
func = args.func
args = vars(args)
func(args["entities"], args["debug"])
if __name__ == '__main__':
main()
|
# Copyright (c) 2014 Wieland Hoffmann
# License: MIT, see LICENSE for details
import argparse
import logging
from . import config
from .indexing import reindex
logger = logging.getLogger("sir")
def watch(args):
raise NotImplementedError
def main():
loghandler = logging.StreamHandler()
formatter = logging.Formatter(fmt="%(threadName)s %(levelname)s: %(message)s")
loghandler.setFormatter(formatter)
logger.addHandler(loghandler)
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--debug", action="store_true")
subparsers = parser.add_subparsers()
reindex_parser = subparsers.add_parser("reindex", help="Reindexes all or a single entity type")
reindex_parser.set_defaults(func=reindex)
reindex_parser.add_argument('--entities', action='append', help='The entities to reindex')
watch_parser = subparsers.add_parser("watch", help="Watches for incoming messages on an AMQP queue")
watch_parser.set_defaults(func=watch)
args = parser.parse_args()
if args.debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
config.read_config()
func = args.func
args = vars(args)
func(args["entities"], args["debug"])
if __name__ == '__main__':
main()
|
Add the disabled and readOnly props directly to the SingleLineInputBase
|
import React, { PureComponent } from 'react';
import InputMask from 'react-input-mask';
import Icon from '../icon';
import SingleLineInputBase from './SingleLineInputBase';
import { IconTimerSmallOutline } from '@teamleader/ui-icons';
const isValidTime = input => RegExp('([0-1][0-9]|[2][0-3]):([0-5][0-9])').test(input);
class TimeInput extends PureComponent {
beforeMaskedValueChange = ({ value: newValue, selection }, { value: oldValue }) => {
if (!isValidTime(newValue)) {
return { value: oldValue, selection };
}
return { value: newValue, selection };
};
render() {
const { disabled, readOnly } = this.props;
return (
<InputMask {...this.props} mask="99:99" maskChar="0" beforeMaskedValueChange={this.beforeMaskedValueChange}>
{inputProps => (
<SingleLineInputBase
{...inputProps}
autoComplete="off"
readOnly={readOnly}
disabled={disabled}
prefix={
<Icon color="neutral" tint="darkest">
<IconTimerSmallOutline />
</Icon>
}
/>
)}
</InputMask>
);
}
}
export default TimeInput;
|
import React, { PureComponent } from 'react';
import InputMask from 'react-input-mask';
import Icon from '../icon';
import SingleLineInputBase from './SingleLineInputBase';
import { IconTimerSmallOutline } from '@teamleader/ui-icons';
const isValidTime = input => RegExp('([0-1][0-9]|[2][0-3]):([0-5][0-9])').test(input);
class TimeInput extends PureComponent {
beforeMaskedValueChange = ({ value: newValue, selection }, { value: oldValue }) => {
if (!isValidTime(newValue)) {
return { value: oldValue, selection };
}
return { value: newValue, selection };
};
render() {
return (
<InputMask {...this.props} mask="99:99" maskChar="0" beforeMaskedValueChange={this.beforeMaskedValueChange}>
{inputProps => (
<SingleLineInputBase
{...inputProps}
autoComplete="off"
prefix={
<Icon color="neutral" tint="darkest">
<IconTimerSmallOutline />
</Icon>
}
/>
)}
</InputMask>
);
}
}
export default TimeInput;
|
Fix the binary packet pool and x2 its capacity
|
package tarantool
type BinaryPacketPool struct {
queue chan *BinaryPacket
}
func newPackedPacketPool() *BinaryPacketPool {
return &BinaryPacketPool{
queue: make(chan *BinaryPacket, 1024),
}
}
func (p *BinaryPacketPool) GetWithID(requestID uint64) (pp *BinaryPacket) {
select {
case pp = <-p.queue:
default:
pp = &BinaryPacket{}
}
pp.Reset()
pp.pool = p
pp.packet.requestID = requestID
return
}
func (p *BinaryPacketPool) Get() *BinaryPacket {
return p.GetWithID(0)
}
func (p *BinaryPacketPool) Put(pp *BinaryPacket) {
pp.pool = nil
select {
case p.queue <- pp:
default:
}
}
func (p *BinaryPacketPool) Close() {
close(p.queue)
}
|
package tarantool
type BinaryPacketPool struct {
queue chan *BinaryPacket
}
func newPackedPacketPool() *BinaryPacketPool {
return &BinaryPacketPool{
queue: make(chan *BinaryPacket, 512),
}
}
func (p *BinaryPacketPool) GetWithID(requestID uint64) (pp *BinaryPacket) {
select {
case pp = <-p.queue:
pp.Reset()
pp.pool = p
default:
pp = &BinaryPacket{}
pp.Reset()
}
pp.packet.requestID = requestID
return
}
func (p *BinaryPacketPool) Get() *BinaryPacket {
return p.GetWithID(0)
}
func (p *BinaryPacketPool) Put(pp *BinaryPacket) {
pp.pool = nil
p.queue <- pp
}
func (p *BinaryPacketPool) Close() {
close(p.queue)
}
|
Add language attributes to html tag
|
<!Doctype html>
<html class="no-js" <?php language_attributes() ?>>
<head>
<title><?php wp_title( '·', true, 'right' ); ?></title>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="cleartype" content="on">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="<?= get_stylesheet_directory_uri(); ?>/assets/images/favicon.ico">
<link rel="apple-touch-icon" href="<?= get_stylesheet_directory_uri(); ?>/assets/images/apple-touch-icon.png">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<header>
<h1><a href="<?= home_url(); ?>"><?php bloginfo( 'name' ); ?></a></h1>
<p><?php bloginfo( 'description' ); ?></p>
<?php wp_nav_menu(); ?>
<?php get_search_form(); ?>
</header>
|
<!Doctype html>
<html class="no-js">
<head>
<title><?php wp_title( '·', true, 'right' ); ?></title>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="cleartype" content="on">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="<?= get_stylesheet_directory_uri(); ?>/assets/images/favicon.ico">
<link rel="apple-touch-icon" href="<?= get_stylesheet_directory_uri(); ?>/assets/images/apple-touch-icon.png">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<header>
<h1><a href="<?= home_url(); ?>"><?php bloginfo( 'name' ); ?></a></h1>
<p><?php bloginfo( 'description' ); ?></p>
<?php wp_nav_menu(); ?>
<?php get_search_form(); ?>
</header>
|
Exclude ja-JP-mac on homepage language select functional test
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'ja-JP-mac', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import random
import pytest
from ..pages.home import HomePage
@pytest.mark.nondestructive
def test_change_language(base_url, selenium):
page = HomePage(base_url, selenium).open()
initial = page.footer.language
# avoid selecting the same language or locales that have homepage redirects
excluded = [initial, 'ja', 'zh-TW', 'zh-CN']
available = [l for l in page.footer.languages if l not in excluded]
new = random.choice(available)
page.footer.select_language(new)
assert new in selenium.current_url, 'Language is not in URL'
assert new == page.footer.language, 'Language has not been selected'
|
ENYO-1948: Fix path to library image asset.
Enyo-DCO-1.1-Signed-off-by: Aaron Tam <aaron.tam@lge.com>
|
var
kind = require('enyo/kind'),
Img = require('enyo/Image'),
Repeater = require('enyo/Repeater');
var
Divider = require('moonstone/Divider'),
Item = require('moonstone/Item'),
Scroller = require('moonstone/Scroller');
module.exports = kind({
name: 'moon.sample.ScrollerHorizontalSample',
classes: 'moon enyo-unselectable enyo-fit',
components: [
{kind: Divider, content: 'Horizontal Scroller'},
{kind: Scroller, vertical: 'hidden', spotlight: 'container', style: 'white-space: nowrap;', components: [
{kind: Repeater, count: '50', components: [
{kind: Item, classes: 'moon-scroller-sample-item enyo', style: 'display:inline-block;', components: [
{kind: Img, src: 'moonstone/images/enyo-icon.png'}
]}
]}
]}
]
});
|
var
kind = require('enyo/kind'),
Img = require('enyo/Image'),
Repeater = require('enyo/Repeater');
var
Divider = require('moonstone/Divider'),
Item = require('moonstone/Item'),
Scroller = require('moonstone/Scroller');
module.exports = kind({
name: 'moon.sample.ScrollerHorizontalSample',
classes: 'moon enyo-unselectable enyo-fit',
components: [
{kind: Divider, content: 'Horizontal Scroller'},
{kind: Scroller, vertical: 'hidden', spotlight: 'container', style: 'white-space: nowrap;', components: [
{kind: Repeater, count: '50', components: [
{kind: Item, classes: 'moon-scroller-sample-item enyo', style: 'display:inline-block;', components: [
{kind: Img, src: '@../images/enyo-icon.png'}
]}
]}
]}
]
});
|
Fix README.rst in wrong place
|
#!/usr/bin/env python
import json
import os
from setuptools import setup, find_packages
def get_requirements_from_pipfile_lock(pipfile_lock=None):
if pipfile_lock is None:
pipfile_lock = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Pipfile.lock')
lock_data = json.load(open(pipfile_lock))
return [package_name for package_name in lock_data.get('default', {}).keys()]
pipfile_lock_requirements = get_requirements_from_pipfile_lock()
setup(
name='dmpy',
version='0.13.3',
description='Distributed Make for Python',
long_description=open('README.rst').read(),
author='Kiran Garimella and Warren Kretzschmar',
author_email='kiran.garimella@gmail.com',
packages=find_packages(),
install_requires=pipfile_lock_requirements,
url='https://github.com/kvg/dmpy',
)
|
#!/usr/bin/env python
import json
import os
from setuptools import setup, find_packages
def get_requirements_from_pipfile_lock(pipfile_lock=None):
if pipfile_lock is None:
pipfile_lock = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Pipfile.lock')
lock_data = json.load(open(pipfile_lock))
return [package_name for package_name in lock_data.get('default', {}).keys()]
pipfile_lock_requirements = get_requirements_from_pipfile_lock()
setup(
name='dmpy',
version='0.13.2',
description=open('README.rst').read(),
author='Kiran Garimella and Warren Kretzschmar',
author_email='kiran.garimella@gmail.com',
packages=find_packages(),
install_requires=pipfile_lock_requirements,
url='https://github.com/kvg/dmpy',
)
|
Use a frozen set for constant.
|
from itertools import chain
import string
from cymbology.alphanum import CHAR_MAP
from cymbology.codes import CINS_CODES
from cymbology.exceptions import CountryCodeError
from cymbology.luhn import _luhnify
from cymbology.validation import SecurityId
CUSIP_FIRST_CHAR = frozenset(chain((c[0] for c in CINS_CODES), string.digits))
class Cusip(SecurityId):
"""CUSIP identification number.
References
----------
https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf
"""
MAX_LEN = 9
def _calculate_checksum(self, sid_):
return _luhnify((CHAR_MAP[c] for c in reversed(sid_)))
def _additional_checks(self, sid_):
if sid_[0] not in CUSIP_FIRST_CHAR:
raise CountryCodeError
def cusip_from_isin(isin):
"""Convert ISIN security identifiers to CUSIP identifiers."""
if not isin.startswith('US'):
raise CountryCodeError
return Cusip().validate(isin[2:-1])
|
from itertools import chain
import string
from cymbology.alphanum import CHAR_MAP
from cymbology.codes import CINS_CODES
from cymbology.exceptions import CountryCodeError
from cymbology.luhn import _luhnify
from cymbology.validation import SecurityId
CUSIP_FIRST_CHAR = set(chain((c[0] for c in CINS_CODES), string.digits))
class Cusip(SecurityId):
"""CUSIP identification number.
References
----------
https://www.cusip.com/pdf/CUSIP_Intro_03.14.11.pdf
"""
MAX_LEN = 9
def _calculate_checksum(self, sid_):
return _luhnify((CHAR_MAP[c] for c in reversed(sid_)))
def _additional_checks(self, sid_):
if sid_[0] not in CUSIP_FIRST_CHAR:
raise CountryCodeError
def cusip_from_isin(isin):
"""Convert ISIN security identifiers to CUSIP identifiers."""
if not isin.startswith('US'):
raise CountryCodeError
return Cusip().validate(isin[2:-1])
|
Add anchor for linking to flash message.
|
<nav class="primary">
<a class="navigation__logo" href="{{{ route('home') }}}"><img src="/dist/images/logo.png" alt="Celebs Gone Good"></a>
@if(Session::has('flash_message'))
<div id="message" class="messages {{ Session::get('flash_message_type', '') }}">{{ Session::get('flash_message') }}</div>
@else
<p class="navigation__tagline">Vote for your favorite celeb who has done kick ass things in the world.</p>
@endif
<ul>
@if($categories)
<li>{{ highlighted_link_to_route('categories.show', $categories[0]->name, [$categories[0]->slug], '/') }}</li>
@for($i = 1; $i < count($categories); $i++)
<li>{{ highlighted_link_to_route('categories.show', $categories[$i]->name, [$categories[$i]->slug]) }}</li>
@endfor
@else
<li>No categories.</li>
@endif
<li>{{ highlighted_link_to_route('write-in.create', 'Write In') }} </li>
</ul>
</nav>
|
<nav class="primary">
<a class="navigation__logo" href="{{{ route('home') }}}"><img src="/dist/images/logo.png" alt="Celebs Gone Good"></a>
@if(Session::has('flash_message'))
<div class="messages {{ Session::get('flash_message_type', '') }}">{{ Session::get('flash_message') }}</div>
@else
<p class="navigation__tagline">Vote for your favorite celeb who has done kick ass things in the world.</p>
@endif
<ul>
@if($categories)
<li>{{ highlighted_link_to_route('categories.show', $categories[0]->name, [$categories[0]->slug], '/') }}</li>
@for($i = 1; $i < count($categories); $i++)
<li>{{ highlighted_link_to_route('categories.show', $categories[$i]->name, [$categories[$i]->slug]) }}</li>
@endfor
@else
<li>No categories.</li>
@endif
<li>{{ highlighted_link_to_route('write-in.create', 'Write In') }} </li>
</ul>
</nav>
|
Fix that removes hover effect on touch devices
|
import gtr from './global-translation.js'
import GraphicsHandler from './graphics-handler.js'
import MouseHandler from './mouse-handler.js'
import {getIsometricCoordinate} from './isometric-math.js'
const CONTAINER = document.querySelector('.graphics-wrapper')
export default class GridInteraction {
constructor () {
this.gh = new GraphicsHandler(CONTAINER)
this.isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints
};
}
clear () {
this.gh.clearCanvas()
}
render () {
const x = MouseHandler.position().x
const y = MouseHandler.position().y
if (!isTouchDevice && x !== this.oldX && y !== this.oldY) {
this.oldX = x
this.oldY = y
const gPos = gtr.toGlobal(x, y)
const isoCoord = getIsometricCoordinate(gPos.x, gPos.y)
this.gh.clearCanvas()
this.gh.fillStyle = 'rgba(0, 0, 0, 0.2)'
this.gh.drawTriangle(isoCoord.a1, isoCoord.a2, isoCoord.right)
}
}
}
|
import gtr from './global-translation.js'
import GraphicsHandler from './graphics-handler.js'
import MouseHandler from './mouse-handler.js'
import {getIsometricCoordinate} from './isometric-math.js'
const CONTAINER = document.querySelector('.graphics-wrapper')
export default class GridInteraction {
constructor () {
this.gh = new GraphicsHandler(CONTAINER)
}
clear () {
this.gh.clearCanvas()
}
render () {
const x = MouseHandler.position().x
const y = MouseHandler.position().y
if (x !== this.oldX && y !== this.oldY) {
this.oldX = x
this.oldY = y
const gPos = gtr.toGlobal(x, y)
const isoCoord = getIsometricCoordinate(gPos.x, gPos.y)
this.gh.clearCanvas()
this.gh.fillStyle = 'rgba(0, 0, 0, 0.2)'
this.gh.drawTriangle(isoCoord.a1, isoCoord.a2, isoCoord.right)
}
}
}
|
Update primary forest widget sentence
|
export default {
widget: 'primaryForest',
title: 'Primary forest in {location}',
categories: ['land-cover'],
types: ['country'],
admins: ['adm0', 'adm1', 'adm2'],
options: {
landCategories: true,
thresholds: true
},
colors: 'extent',
metaKey: 'widget_primary_forest',
datasets: [
// tree cover
{
dataset: '044f4af8-be72-4999-b7dd-13434fc4a394',
layers: {
2010: '78747ea1-34a9-4aa7-b099-bdb8948200f4',
2000: 'c05c32fd-289c-4b20-8d73-dc2458234e04'
}
}
],
sortOrder: {
landCover: 4
},
sentences: {
initial:
'As of 2001, {percentage} of {location} total tree cover was <b>primary forest</b>.',
withIndicator:
'As of 2001, {percentage} of {location} total tree cover in {indicator} was <b>primary forest</b>.'
},
whitelists: {
adm0: ['IDN', 'COD']
}
};
|
export default {
widget: 'primaryForest',
title: 'Primary forest in {location}',
categories: ['land-cover'],
types: ['country'],
admins: ['adm0', 'adm1', 'adm2'],
options: {
landCategories: true,
thresholds: true
},
colors: 'extent',
metaKey: 'widget_primary_forest',
datasets: [
// tree cover
{
dataset: '044f4af8-be72-4999-b7dd-13434fc4a394',
layers: {
2010: '78747ea1-34a9-4aa7-b099-bdb8948200f4',
2000: 'c05c32fd-289c-4b20-8d73-dc2458234e04'
}
}
],
sortOrder: {
landCover: 4
},
sentences: {
initial:
'As of {extentYear}, {percentage} of {location} total tree cover was <b>primary forest</b>.',
withIndicator:
'As of {extentYear}, {percentage} of {location} total tree cover in {indicator} was <b>primary forest</b>.'
},
whitelists: {
adm0: ['IDN', 'COD']
}
};
|
Remove unused property in query state
|
package SW9.abstractions;
import SW9.utility.colors.Color;
public enum QueryState {
SUCCESSFUL(Color.GREEN, Color.Intensity.I700),
ERROR(Color.RED, Color.Intensity.I700),
RUNNING(Color.GREY_BLUE, Color.Intensity.I600),
UNKNOWN(Color.GREY, Color.Intensity.I600),
SYNTAX_ERROR(Color.PURPLE, Color.Intensity.I700);
private final Color color;
private final Color.Intensity colorIntensity;
QueryState(final Color color, final Color.Intensity colorIntensity) {
this.color = color;
this.colorIntensity = colorIntensity;
}
public Color getColor() {
return color;
}
public Color.Intensity getColorIntensity() {
return colorIntensity;
}
}
|
package SW9.abstractions;
import SW9.utility.colors.Color;
public enum QueryState {
SUCCESSFUL(Color.GREEN, Color.Intensity.I700, "✓"),
ERROR(Color.RED, Color.Intensity.I700, "✘"),
RUNNING(Color.GREY_BLUE, Color.Intensity.I600, "···"),
UNKNOWN(Color.GREY, Color.Intensity.I600, "?"),
SYNTAX_ERROR(Color.PURPLE, Color.Intensity.I700, "!");
private final Color color;
private final Color.Intensity colorIntensity;
private final String indicator;
QueryState(final Color color, final Color.Intensity colorIntensity, final String indicator) {
this.color = color;
this.colorIntensity = colorIntensity;
this.indicator = indicator;
}
public Color getColor() {
return color;
}
public Color.Intensity getColorIntensity() {
return colorIntensity;
}
public String getIndicator() {
return indicator;
}
}
|
Fix IE not allowing innerHTML table elements (except for a cell) descendants.
|
import assign from '../util/assign';
import init from './init';
import registry from '../global/registry';
var specialMap = {
caption: 'table',
dd: 'dl',
dt: 'dl',
li: 'ul',
tbody: 'table',
td: 'tr',
thead: 'table',
tr: 'tbody'
};
function fixIeNotAllowingInnerHTMLOnTableElements (tag, html) {
var target = document.createElement('div');
var levels = 0;
while (tag) {
html = `<${tag}>${html}</${tag}>`;
tag = specialMap[tag];
++levels;
}
target.innerHTML = html;
for (let a = 0; a <= levels; a++) {
target = target.firstElementChild;
}
return target;
}
function matchTag (dom) {
var tag = dom.match(/\s*<([^\s>]+)/);
return tag && tag[1];
}
function createFromHtml (html) {
var tag = specialMap[matchTag(html)];
var par = document.createElement(tag || 'div');
par.innerHTML = html;
return init(par.firstElementChild || fixIeNotAllowingInnerHTMLOnTableElements(tag, html));
}
function createFromName (name) {
var ctor = registry.get(name);
return ctor && ctor() || document.createElement(name);
}
export default function (name, props) {
name = name.trim();
return assign(name[0] === '<' ? createFromHtml(name) : createFromName(name), props);
}
|
import assign from '../util/assign';
import init from './init';
import registry from '../global/registry';
var specialMap = {
caption: 'table',
dd: 'dl',
dt: 'dl',
li: 'ul',
tbody: 'table',
td: 'tr',
thead: 'table',
tr: 'tbody'
};
function matchTag (dom) {
var tag = dom.match(/\s*<([^\s>]+)/);
return tag && tag[1];
}
function createFromHtml (html) {
var par = document.createElement(specialMap[matchTag(html)] || 'div');
par.innerHTML = html;
return init(par.firstElementChild);
}
function createFromName (name) {
var ctor = registry.get(name);
return ctor && ctor() || document.createElement(name);
}
export default function (name, props) {
name = name.trim();
return assign(name[0] === '<' ? createFromHtml(name) : createFromName(name), props);
}
|
Remove spaces from basic e2e tests.
|
'use strict';
describe('my app', function() {
browser.get('index.html');
it('should automatically redirect to /play when location hash/fragment is empty', function() {
expect(browser.getLocationAbsUrl()).toMatch("/play");
});
describe('play', function() {
beforeEach(function() {
browser.get('index.html#/play');
});
it('should render view1 when user navigates to /view1', function() {
expect(element.all(by.css('[ng-view] h3')).first().getText()).
toMatch(/playing/i);
});
});
describe('preferences', function() {
beforeEach(function() {
browser.get('index.html#/preferences');
});
it('should have the difficulty sections', function() {
expect(element.all(by.css('[ng-view] h3')).first().getText()).
toMatch(/difficulty/i);
});
it('should have the characters sections', function() {
expect(element.all(by.css('[ng-view] h3')).last().getText()).
toMatch(/characters/i);
});
});
});
|
'use strict';
/* https://github.com/angular/protractor/blob/master/docs/toc.md */
describe('my app', function() {
browser.get('index.html');
it('should automatically redirect to /play when location hash/fragment is empty', function() {
expect(browser.getLocationAbsUrl()).toMatch("/play");
});
describe('play', function() {
beforeEach(function() {
browser.get('index.html#/play');
});
it('should render view1 when user navigates to /view1', function() {
expect(element.all(by.css('[ng-view] h3')).first().getText()).
toMatch(/playing/i);
});
});
describe('preferences', function() {
beforeEach(function() {
browser.get('index.html#/preferences');
});
it('should have the difficulty sections', function() {
expect(element.all(by.css('[ng-view] h3')).first().getText()).
toMatch(/difficulty/i);
});
it('should have the characters sections', function() {
expect(element.all(by.css('[ng-view] h3')).last().getText()).
toMatch(/characters/i);
});
});
});
|
Move MonteCarlo move to choose_move
|
import random
from collections import defaultdict, Counter
from . import Player
from ..util import utility
class MonteCarlo(Player):
name = 'MonteCarlo'
def __init__(self, n_sims=1000):
self.n_sims = n_sims
def __repr__(self):
return type(self).name
def __str__(self):
return type(self).name
##########
# Player #
##########
def choose_move(self, game):
counter = defaultdict(int)
for i in range(self.n_sims):
for move in game.legal_moves():
new_game = game.copy()
new_game.make_move(move)
while not new_game.is_over():
rand_move = random.choice(new_game.legal_moves())
new_game.make_move(rand_move)
counter[move] += utility(new_game, game.cur_player())
best_move, count = Counter(counter).most_common(1)[0]
return best_move
|
import random
from collections import defaultdict, Counter
from . import Player
from ..util import utility
class MonteCarlo(Player):
name = 'MonteCarlo'
def __init__(self, n_sims=1000):
self.n_sims = n_sims
def __repr__(self):
return type(self).name
def __str__(self):
return type(self).name
def move(self, game):
counter = defaultdict(int)
for i in range(self.n_sims):
for move in game.legal_moves():
new_game = game.copy()
new_game.make_move(move)
while not new_game.is_over():
rand_move = random.choice(new_game.legal_moves())
new_game.make_move(rand_move)
counter[move] += utility(new_game, game.cur_player())
m = Counter(counter).most_common(1)
return m[0][0]
##########
# Player #
##########
def choose_move(self, game):
return self.move(game)
|
Switch toMatch() to "to match" in the case of a regex on the RHS.
|
const unexpected = require('unexpected');
const baseExpect = unexpected.clone();
baseExpect.addAssertion(
'<string> to jest match <string>',
(expect, subject, value) => {
expect.errorMode = 'bubble';
return expect(subject, 'to contain', value);
}
);
baseExpect.addAssertion(
'<string> to jest match <regexp>',
(expect, subject, value) => {
expect.errorMode = 'bubble';
return expect(subject, 'to match', value);
}
);
function withFlags(assertion, flags) {
return flags.not ? `not ${assertion}` : assertion;
}
module.exports = function expect(subject) {
const expect = baseExpect;
const flags = {
not: false
};
const buildAssertion = assertion => {
return value => {
return expect(subject, withFlags(assertion, flags), value);
};
};
return {
toBe: buildAssertion('to be'),
toEqual: buildAssertion('to equal'),
toMatch: buildAssertion('to jest match'),
get not() {
flags.not = true;
return this;
}
};
};
|
const unexpected = require('unexpected');
const baseExpect = unexpected.clone();
baseExpect.addAssertion(
'<string> to jest match <string>',
(expect, subject, value) => {
expect.errorMode = 'bubble';
return expect(subject, 'to contain', value);
}
);
baseExpect.addAssertion(
'<string> to jest match <regexp>',
(expect, subject, value) => {
expect.errorMode = 'bubble';
return expect(subject, 'to satisfy', value);
}
);
function withFlags(assertion, flags) {
return flags.not ? `not ${assertion}` : assertion;
}
module.exports = function expect(subject) {
const expect = baseExpect;
const flags = {
not: false
};
const buildAssertion = assertion => {
return value => {
return expect(subject, withFlags(assertion, flags), value);
};
};
return {
toBe: buildAssertion('to be'),
toEqual: buildAssertion('to equal'),
toMatch: buildAssertion('to jest match'),
get not() {
flags.not = true;
return this;
}
};
};
|
[HOTFIX] Remove replaces line on 0001_squashed
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Channel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('text', models.TextField(max_length=2000)),
('datetime', models.DateTimeField()),
('channel', models.ForeignKey(to='chat.Channel')),
('username', models.CharField(max_length=20)),
],
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
replaces = [(b'chat', '0001_squashed_0008_auto_20150702_1437'), (b'chat', '0002_auto_20150707_1647')]
dependencies = [
]
operations = [
migrations.CreateModel(
name='Channel',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('text', models.TextField(max_length=2000)),
('datetime', models.DateTimeField()),
('channel', models.ForeignKey(to='chat.Channel')),
('username', models.CharField(max_length=20)),
],
),
]
|
Return new CountResult on getResult, and use long instead of CountResult
object internally
|
package mil.nga.giat.geowave.core.store.query.aggregate;
import mil.nga.giat.geowave.core.index.Persistable;
public class CountAggregation<T> implements
Aggregation<Persistable, CountResult, T>
{
private long count = Long.MIN_VALUE;
public CountAggregation() {}
public boolean isSet() {
return count != Long.MIN_VALUE;
}
@Override
public String toString() {
final StringBuffer buffer = new StringBuffer();
buffer.append(
"count[count=").append(
count);
buffer.append("]");
return buffer.toString();
}
@Override
public void aggregate(
final T entry ) {
if (!isSet()) {
count = 0;
}
count += 1;
}
@Override
public Persistable getParameters() {
return null;
}
@Override
public CountResult getResult() {
if (!isSet()) {
return null;
}
return new CountResult(count);
}
@Override
public void setParameters(
final Persistable parameters ) {}
@Override
public void clearResult() {
count = 0;
}
}
|
package mil.nga.giat.geowave.core.store.query.aggregate;
import mil.nga.giat.geowave.core.index.Persistable;
public class CountAggregation<T> implements
Aggregation<Persistable, CountResult, T>
{
private CountResult countResult = new CountResult();
public CountAggregation() {}
@Override
public String toString() {
return countResult.toString();
}
@Override
public void aggregate(
final T entry ) {
if (!countResult.isSet()) {
countResult.count = 0;
}
countResult.count += 1;
}
@Override
public Persistable getParameters() {
return null;
}
@Override
public CountResult getResult() {
if (!countResult.isSet()) {
return null;
}
return countResult;
}
@Override
public void setParameters(
final Persistable parameters ) {}
@Override
public void clearResult() {
countResult.count = 0;
}
}
|
Fix group by style issue
https://github.com/rancher/rancher/issues/13018
|
import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { computed, get, set } from '@ember/object';
import layout from './template';
export default Component.extend({
layout,
scope: service(),
fullColspan: null,
afterName: 0,
showState: false,
afterState: 0,
alignState: 'text-center',
showActions: true,
nameSpan: null,
nodes: null,
nodeId: null,
tagName: '',
didReceiveAttrs() {
const nodes = get(this, 'nodes');
const nodeId = get(this, 'nodeId');
if (nodes && nodeId) {
const clusterId = get(this, 'scope.currentCluster.id');
const targetNode = nodes.find(n => n.id === nodeId && n.clusterId === clusterId);
set(this, 'model', targetNode);
}
const nameSpan = get(this,'fullColspan') -
( get(this, 'afterName') ? 1 : 0 ) -
( get(this, 'showState') ? 1 : 0 ) -
( get(this, 'afterState') ? 1 : 0 ) -
( get(this, 'showActions') ? 1 : 0 );
set(this, 'nameSpan', nameSpan);
},
});
|
import Component from '@ember/component';
import { inject as service } from '@ember/service';
import { computed, get, set } from '@ember/object';
import layout from './template';
export default Component.extend({
layout,
scope: service(),
fullColspan: null,
afterName: 0,
showState: false,
afterState: 0,
alignState: 'text-center',
showActions: true,
nodes: null,
nodeId: null,
tagName: '',
didReceiveAttrs() {
const nodes = get(this, 'nodes');
const nodeId = get(this, 'nodeId');
if (nodes && nodeId) {
const clusterId = get(this, 'scope.currentCluster.id');
const targetNode = nodes.find(n => n.id === nodeId && n.clusterId === clusterId);
set(this, 'model', targetNode);
}
},
});
|
Prepare for next development cycle
|
#!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
setup(
name="bentoo",
description="Benchmarking tools",
version="0.12.dev",
packages=find_packages(),
scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py",
"scripts/bentoo-collector.py", "scripts/bentoo-analyser.py",
"scripts/bentoo-metric.py", "scripts/bentoo-quickstart.py"],
package_data={
'': ['*.adoc', '*.rst', '*.md']
},
author="Zhang YANG",
author_email="zyangmath@gmail.com",
license="PSF",
keywords="Benchmark;Performance Analysis",
url="http://github.com/ProgramFan/bentoo"
)
|
#!/usr/bin/env python
# coding: utf-8
from setuptools import setup, find_packages
setup(
name="bentoo",
description="Benchmarking tools",
version="0.11",
packages=find_packages(),
scripts=["scripts/bentoo-generator.py", "scripts/bentoo-runner.py",
"scripts/bentoo-collector.py", "scripts/bentoo-analyser.py",
"scripts/bentoo-metric.py", "scripts/bentoo-quickstart.py"],
package_data={
'': ['*.adoc', '*.rst', '*.md']
},
author="Zhang YANG",
author_email="zyangmath@gmail.com",
license="PSF",
keywords="Benchmark;Performance Analysis",
url="http://github.com/ProgramFan/bentoo"
)
|
Load app configs for Slacker
|
"""
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker, DEFAULT_TIMEOUT
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app):
"""
Initialize the app in Flask.
"""
app.config.setdefault('SLACKER_TIMEOUT', DEFAULT_TIMEOUT)
if 'SLACKER_TOKEN' not in app.config:
raise Exception('Missing SLACKER_TOKEN in your config.')
token = app.config['SLACKER_TOKEN']
timeout = app.config['SLACKER_TIMEOUT']
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(token, timeout=timeout)
|
"""
flask_slacker
~~~~~~~~~~~~~
A Flask extension for using Slacker.
:copyright: (c) 2017 Matheus Rosa
:license: MIT, see LICENSE for more details.
"""
from slacker import Slacker as BaseSlacker
__version__ = '0.0.1'
class Slacker(object):
def __init__(self, app=None, **kwargs):
"""Initialize the Slacker interface.
:param app: Flask application
"""
if app is not None:
self.init_app(app)
def init_app(self, app, config=None):
"""
Initialize the app in Flask.
"""
if not (config is None or isinstance(config, dict)):
raise ValueError("`config` must be an instance of dict or None")
# register application within app
app.extensions = getattr(app, 'extensions', {})
app.extensions['slack'] = BaseSlacker(**config)
|
Call module.runSetters() after any meteor/tools modules load.
|
// Install ES2015-complaint polyfills for Object, Array, String, Function,
// Symbol, Map, Set, and Promise, patching the native implementations when
// they are available.
require("meteor-ecmascript-runtime");
require("./install-promise.js");
// Verify that the babel-runtime package is available to be required.
// The .join("/") prevents babel-plugin-transform-runtime from
// "intelligently" converting this to an import statement.
var regenerator = require([
"babel-runtime",
"regenerator"
].join("/"));
// Use Promise.asyncApply to wrap calls to runtime.async so that the
// entire async function will run in its own Fiber, not just the code that
// comes after the first await.
var realAsync = regenerator.async;
regenerator.async = function () {
return Promise.asyncApply(realAsync, regenerator, arguments);
};
// Install global.meteorBabelHelpers so that the compiler doesn't need to
// add boilerplate at the top of every file.
require("meteor-babel").defineHelpers();
var Mp = module.constructor.prototype;
var moduleLoad = Mp.load;
Mp.load = function (filename) {
var result = moduleLoad.apply(this, arguments);
var runSetters = this.runSetters || this.runModuleSetters;
if (typeof runSetters === "function") {
// Make sure we call module.runSetters (or module.runModuleSetters, a
// legacy synonym) whenever a module finishes loading.
runSetters.call(this);
}
return result;
};
// Installs source map support with a hook to add functions to look for
// source maps in custom places.
require('./source-map-retriever-stack.js');
|
// Install ES2015-complaint polyfills for Object, Array, String, Function,
// Symbol, Map, Set, and Promise, patching the native implementations when
// they are available.
require("meteor-ecmascript-runtime");
require("./install-promise.js");
// Verify that the babel-runtime package is available to be required.
// The .join("/") prevents babel-plugin-transform-runtime from
// "intelligently" converting this to an import statement.
var regenerator = require([
"babel-runtime",
"regenerator"
].join("/"));
// Use Promise.asyncApply to wrap calls to runtime.async so that the
// entire async function will run in its own Fiber, not just the code that
// comes after the first await.
var realAsync = regenerator.async;
regenerator.async = function () {
return Promise.asyncApply(realAsync, regenerator, arguments);
};
// Install global.meteorBabelHelpers so that the compiler doesn't need to
// add boilerplate at the top of every file.
require("meteor-babel").defineHelpers();
// Installs source map support with a hook to add functions to look for
// source maps in custom places.
require('./source-map-retriever-stack.js');
|
Make access to the parameters static
|
<?php
/**
* File DbConfiguration.php
*
* @category
* @package
* @author Ivanis Kouamé <ivanis.kouame@smile.fr>
* @copyright 2015 Smile
*/
namespace Hipay\SilexIntegration\Configuration;
/**
* Class DbConfiguration
*
* @author Ivanis Kouamé <ivanis.kouame@smile.fr>
* @copyright 2015 Smile
*/
class DbConfiguration
{
public function getHost()
{
return ParameterAccessor::getParameter('db.host');
}
public function getPort()
{
return ParameterAccessor::getParameter('db.port');
}
public function getUsername()
{
return ParameterAccessor::getParameter('db.username');
}
public function getPassword()
{
return ParameterAccessor::getParameter('db.password');
}
public function getDatabaseName()
{
return ParameterAccessor::getParameter('db.name');
}
public function getDebug()
{
return ParameterAccessor::getParameter('doctrine.debug');
}
}
|
<?php
/**
* File DbConfiguration.php
*
* @category
* @package
* @author Ivanis Kouamé <ivanis.kouame@smile.fr>
* @copyright 2015 Smile
*/
namespace Hipay\SilexIntegration\Configuration;
class DbConfiguration extends AbstractConfiguration
{
public function getHost()
{
return parent::$parameters['db.host'];
}
public function getPort()
{
return parent::$parameters['db.port'];
}
public function getUsername()
{
return parent::$parameters['db.username'];
}
public function getPassword()
{
return parent::$parameters['db.password'];
}
public function getDatabaseName()
{
return parent::$parameters['db.name'];
}
public function getDebug()
{
return parent::$parameters['doctrine.debug'];
}
}
|
[Refactor] Set status to default to true
|
var Sequelize = require("sequelize");
module.exports = function(sequelize, tableConfig) {
return sequelize.define('UserUrl', {
email: {
type: Sequelize.STRING,
allowNull: false
},
webImage: {
type: Sequelize.STRING
},
cropImage: {
type: Sequelize.STRING,
allowNull: false
},
cropHeight: {
type: Sequelize.INTEGER,
allowNull: false
},
cropWidth: {
type: Sequelize.INTEGER,
allowNull: false
},
cropOriginX: {
type: Sequelize.INTEGER,
allowNull: false
},
cropOriginY: {
type: Sequelize.INTEGER,
allowNull: false
},
status: {
type: Sequelize.BOOLEAN,
defaultValue: true
},
frequency: {
type: Sequelize.INTEGER,
defaultValue: 5
},
}, tableConfig)
}
|
var Sequelize = require("sequelize");
module.exports = function(sequelize, tableConfig) {
return sequelize.define('UserUrl', {
email: {
type: Sequelize.STRING,
allowNull: false
},
webImage: {
type: Sequelize.STRING
},
cropImage: {
type: Sequelize.STRING,
allowNull: false
},
cropHeight: {
type: Sequelize.INTEGER,
allowNull: false
},
cropWidth: {
type: Sequelize.INTEGER,
allowNull: false
},
cropOriginX: {
type: Sequelize.INTEGER,
allowNull: false
},
cropOriginY: {
type: Sequelize.INTEGER,
allowNull: false
},
status: Sequelize.BOOLEAN,
frequency: {
type: Sequelize.INTEGER,
defaultValue: 5
},
}, tableConfig)
}
|
Use a watch function instead of adding submission to scope
|
'use strict';
module.exports = function ($interpolate, $parse) {
return {
require: '^bdSubmit',
restrict: 'A',
compile: function (element, attributes) {
if (!attributes.type) {
attributes.$set('type', 'submit');
}
return function (scope, element, attributes, controller) {
var original = element.text();
function ngDisabled () {
return attributes.ngDisabled && !!$parse(attributes.ngDisabled)(scope);
}
scope.$watch(function () {
return controller.pending;
}, function (pending) {
attributes.$set('disabled', pending || ngDisabled());
element.text($interpolate(pending ? attributes.pending : original)(scope));
});
};
}
};
};
module.exports.$inject = ['$interpolate', '$parse'];
|
'use strict';
module.exports = function ($interpolate, $parse) {
return {
require: '^bdSubmit',
restrict: 'A',
compile: function (element, attributes) {
if (!attributes.type) {
attributes.$set('type', 'submit');
}
return function (scope, element, attributes, controller) {
var original = element.text();
scope.submission = controller;
function ngDisabled () {
return attributes.ngDisabled && !!$parse(attributes.ngDisabled)(scope);
}
scope.$watch('submission.pending', function (pending) {
attributes.$set('disabled', pending || ngDisabled());
element.text($interpolate(pending ? attributes.pending : original)(scope));
});
};
}
};
};
module.exports.$inject = ['$interpolate', '$parse'];
|
Update testing path to support new /$root proxy route
|
define({
proxyPort: 9010,
proxyUrl: 'http://localhost:9010/',
initialBaseUrl: '../../',
excludeInstrumentation: /^(?:node_modules|script\/tests)\//,
tunnel: 'NullTunnel',
loaderOptions: {
packages: [
{
name: 'Wee',
location: 'script',
main: 'wee.js'
}
]
},
functionalSuites: [
],
suites: [
'script/tests/unit/wee',
'script/tests/unit/wee.assets',
'script/tests/unit/wee.chain',
'script/tests/unit/wee.data',
'script/tests/unit/wee.dom',
'script/tests/unit/wee.events',
'script/tests/unit/wee.routes',
'script/tests/unit/wee.screen',
'script/tests/unit/wee.view'
],
environments: [
{
browserName: 'chrome'
}
]
});
|
define({
proxyPort: 9010,
proxyUrl: 'http://localhost:9010/',
initialBaseUrl: '../../',
excludeInstrumentation: /^(?:node_modules|script\/tests)\//,
tunnel: 'NullTunnel',
loaderOptions: {
packages: [
{
name: 'Wee',
location: '/script',
main: 'wee.js'
}
]
},
functionalSuites: [
],
suites: [
'script/tests/unit/wee',
'script/tests/unit/wee.assets',
'script/tests/unit/wee.chain',
'script/tests/unit/wee.data',
'script/tests/unit/wee.dom',
'script/tests/unit/wee.events',
'script/tests/unit/wee.routes',
'script/tests/unit/wee.screen',
'script/tests/unit/wee.view'
],
environments: [
{
browserName: 'chrome'
}
]
});
|
Drop EOL Python 3.3, add 3.6
|
__VERSION__ = '1.0.3'
from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except OSError:
# Stolen from pypandoc: if pandoc is not installed, fallback to using raw contents
long_description = open('README.md').read()
except ImportError:
long_description = None
setup(
name='python-editor',
version=__VERSION__,
description="Programmatically open an editor, capture the result.",
long_description=long_description,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries',
],
keywords='editor library vim emacs',
author='Peter Ruibal',
author_email='ruibalp@gmail.com',
url='https://github.com/fmoo/python-editor',
license='Apache',
py_modules=[
'editor',
],
requires=[
#'six',
],
)
|
__VERSION__ = '1.0.3'
from setuptools import setup
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except OSError:
# Stolen from pypandoc: if pandoc is not installed, fallback to using raw contents
long_description = open('README.md').read()
except ImportError:
long_description = None
setup(
name='python-editor',
version=__VERSION__,
description="Programmatically open an editor, capture the result.",
long_description=long_description,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Software Development :: Libraries',
],
keywords='editor library vim emacs',
author='Peter Ruibal',
author_email='ruibalp@gmail.com',
url='https://github.com/fmoo/python-editor',
license='Apache',
py_modules=[
'editor',
],
requires=[
#'six',
],
)
|
Build the error message earlier
|
package org.rocket.network.props;
import org.rocket.network.MutProp;
import org.rocket.network.NetworkClient;
import org.rocket.network.PropId;
import org.rocket.network.PropValidator;
public class PropPresenceValidator implements PropValidator {
private final PropId pid;
private String messageError;
public PropPresenceValidator(PropPresence annotation) {
this.pid = PropIds.type(annotation.value());
this.messageError = String.format(
"Prop %s must have a value", pid);
}
@Override
public void validate(NetworkClient client) {
MutProp<Object> prop = client.getProp(pid);
if (!prop.isDefined()) {
throw new AssertionError(messageError);
}
}
}
|
package org.rocket.network.props;
import org.rocket.network.MutProp;
import org.rocket.network.NetworkClient;
import org.rocket.network.PropId;
import org.rocket.network.PropValidator;
public class PropPresenceValidator implements PropValidator {
private final PropId pid;
public PropPresenceValidator(PropPresence annotation) {
this.pid = PropIds.type(annotation.value());
}
@Override
public void validate(NetworkClient client) {
MutProp<Object> prop = client.getProp(pid);
if (!prop.isDefined()) {
throw new AssertionError(String.format(
"Prop %s must have a value",
prop.getId()));
}
}
}
|
Refactor function for rounding currency
|
/*
Returns letters with currencies to shorten them.
Taken from: http://stackoverflow.com/questions/36734201/how-to-convert-numbers-to-million-in-javascript
*/
export default function currencyRounder(rawValue) {
if (Math.abs(Number(rawValue)) >= 1.0e+9) {
return Math.round(Math.abs(Number(rawValue)) / 1.0e+9) + "B";
}
if (Math.abs(Number(rawValue)) >= 1.0e+6){
return Math.round(Math.abs(Number(rawValue)) / 1.0e+6) + "M";
}
if (Math.abs(Number(rawValue)) >= 1.0e+3) {
return Math.round(Math.abs(Number(rawValue)) / 1.0e+3) + "K";
}
return Math.abs(Number(rawValue));
}
|
/*
Returns letters with currencies to shorten them.
Taken from: http://stackoverflow.com/questions/36734201/how-to-convert-numbers-to-million-in-javascript
*/
export default function currencyRounder(rawValue) {
// Nine Zeroes for Billions
return Math.abs(Number(rawValue)) >= 1.0e+9
? Math.round(Math.abs(Number(rawValue)) / 1.0e+9) + "B"
// Six Zeroes for Millions
: Math.abs(Number(rawValue)) >= 1.0e+6
? Math.round(Math.abs(Number(rawValue)) / 1.0e+6) + "M"
// Three Zeroes for Thousands
: Math.abs(Number(rawValue)) >= 1.0e+3
? Math.round(Math.abs(Number(rawValue)) / 1.0e+3) + "K"
// Otherwise return the number
: Math.abs(Number(rawValue));
}
|
MNT: Remove coverage on replay; development is suspended.
|
#!/usr/bin/env python
# This file is closely based on tests.py from matplotlib
#
# This allows running the matplotlib tests from the command line: e.g.
#
# $ python tests.py -v -d
#
# The arguments are identical to the arguments accepted by nosetests.
#
# See https://nose.readthedocs.org/ for a detailed description of
# these options.
try:
import enaml.qt
del enaml
except ImportError:
pass
import nose
from dataportal.testing.noseclasses import KnownFailure
plugins = [KnownFailure]
env = {"NOSE_WITH_COVERAGE": 1,
'NOSE_COVER_PACKAGE': ['dataportal'],
'NOSE_COVER_HTML': 1}
# Nose doesn't automatically instantiate all of the plugins in the
# child processes, so we have to provide the multiprocess plugin with
# a list.
from nose.plugins import multiprocess
multiprocess._instantiate_plugins = plugins
def run():
nose.main(addplugins=[x() for x in plugins], env=env)
if __name__ == '__main__':
run()
|
#!/usr/bin/env python
# This file is closely based on tests.py from matplotlib
#
# This allows running the matplotlib tests from the command line: e.g.
#
# $ python tests.py -v -d
#
# The arguments are identical to the arguments accepted by nosetests.
#
# See https://nose.readthedocs.org/ for a detailed description of
# these options.
try:
import enaml.qt
del enaml
except ImportError:
pass
import nose
from dataportal.testing.noseclasses import KnownFailure
plugins = [KnownFailure]
env = {"NOSE_WITH_COVERAGE": 1,
'NOSE_COVER_PACKAGE': ['dataportal', 'replay'],
'NOSE_COVER_HTML': 1}
# Nose doesn't automatically instantiate all of the plugins in the
# child processes, so we have to provide the multiprocess plugin with
# a list.
from nose.plugins import multiprocess
multiprocess._instantiate_plugins = plugins
def run():
nose.main(addplugins=[x() for x in plugins], env=env)
if __name__ == '__main__':
run()
|
Update export building fires command.
|
from django.core.management.base import BaseCommand
from firecares.firestation.models import FireDepartment
class Command(BaseCommand):
"""
This command is used to export data that department heat maps visualize.
"""
help = 'Creates a sql file to export building fires from.'
def handle(self, *args, **options):
vals = FireDepartment.objects.filter(fdid__isnull=False, state__isnull=False).exclude(fdid__exact='')
sql = """
\COPY (select alarm, a.inc_type, alarms,ff_death, oth_death, ST_X(geom) as x, st_y(geom) as y from buildingfires a left join incidentaddress b using (state, inc_date, exp_no, fdid, inc_no) where state='{state}' and fdid='{fdid}') to PROGRAM 'aws s3 cp - s3://firecares-pipeline/heatmaps/{id}-building-fires.csv --acl=\"public-read\"' DELIMITER ',' CSV HEADER;
"""
for fd in vals:
self.stdout.write(sql.format(fdid=fd.fdid, state=fd.state, id=fd.id) + '\n')
|
from django.core.management.base import BaseCommand
from firecares.firestation.models import FireDepartment
class Command(BaseCommand):
"""
This command is used to export data that department heat maps visualize.
"""
help = 'Creates a sql file to export building fires from.'
def handle(self, *args, **options):
vals = FireDepartment.objects.filter(fdid__isnull=False, state__isnull=False).exclude(fdid__exact='')
sql = """\COPY (select alarm, a.inc_type, alarms,ff_death, oth_death, ST_X(geom) as x, st_y(geom) as y from buildingfires a left join incidentaddress b using (state, inc_date, exp_no, fdid, inc_no) where state='{state}' and fdid='{fdid}') to '/tmp/data/{id}-building-fires.csv' DELIMITER ',' CSV HEADER;"""
for fd in vals:
self.stdout.write(sql.format(fdid=fd.fdid, state=fd.state, id=fd.id) + '\n')
|
Increment version for new migrations..
|
"""Setup file for easy installation"""
import os
from setuptools import setup, find_packages
from tests import test_cmd
ROOT = os.path.dirname(__file__)
setup(
name="django-payzen",
version="1.0.6",
description="Django app to manage payments with Payzen ETP",
license='MIT',
author="Bertrand Svetchine",
author_email="bertrand.svetchine@gmail.com",
url="https://github.com/bsvetchine/django-payzen",
packages=find_packages(),
include_package_data=True,
install_requires=["Django"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Framework :: Django",
"Topic :: Software Development"],
cmdclass={'test': test_cmd.TestCommand}
)
|
"""Setup file for easy installation"""
import os
from setuptools import setup, find_packages
from tests import test_cmd
ROOT = os.path.dirname(__file__)
setup(
name="django-payzen",
version="1.0.5",
description="Django app to manage payments with Payzen ETP",
license='MIT',
author="Bertrand Svetchine",
author_email="bertrand.svetchine@gmail.com",
url="https://github.com/bsvetchine/django-payzen",
packages=find_packages(),
include_package_data=True,
install_requires=["Django"],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Framework :: Django",
"Topic :: Software Development"],
cmdclass={'test': test_cmd.TestCommand}
)
|
Remove path again, should be injected
|
<?php
/**
* @file
*/
namespace CultuurNet\UDB3\UDB2;
use CultuurNet\Auth\TokenCredentials;
final class EntryAPIFactory
{
/**
* @var Consumer
*/
private $consumer;
/**
* @param Consumer $consumer
*/
public function __construct(
Consumer $consumer
)
{
$this->consumer = $consumer;
}
/**
* @param TokenCredentials $tokenCredentials
* @return \CultureFeed_EntryApi
*/
public function withTokenCredentials(TokenCredentials $tokenCredentials)
{
$consumerCredentials = $this->consumer->getConsumerCredentials();
$oauthClient = new \CultureFeed_DefaultOAuthClient(
$consumerCredentials->getKey(),
$consumerCredentials->getSecret(),
$tokenCredentials->getToken(),
$tokenCredentials->getSecret()
);
$oauthClient->setEndpoint($this->consumer->getTargetUrl());
return new \CultureFeed_EntryApi($oauthClient);
}
}
|
<?php
/**
* @file
*/
namespace CultuurNet\UDB3\UDB2;
use CultuurNet\Auth\TokenCredentials;
final class EntryAPIFactory
{
/**
* @var Consumer
*/
private $consumer;
/**
* @param Consumer $consumer
*/
public function __construct(
Consumer $consumer
)
{
$this->consumer = $consumer;
}
/**
* @param TokenCredentials $tokenCredentials
* @return \CultureFeed_EntryApi
*/
public function withTokenCredentials(TokenCredentials $tokenCredentials)
{
$consumerCredentials = $this->consumer->getConsumerCredentials();
$oauthClient = new \CultureFeed_DefaultOAuthClient(
$consumerCredentials->getKey(),
$consumerCredentials->getSecret(),
$tokenCredentials->getToken(),
$tokenCredentials->getSecret()
);
$oauthClient->setEndpoint($this->consumer->getTargetUrl() . '/entry/test.rest.uitdatabank.be/api/v2/');
return new \CultureFeed_EntryApi($oauthClient);
}
}
|
Bump snapshot version in Collect client
|
import Objects from 'utils/Objects'
export default class Constants {
static APP_VERSION = Objects.defaultIfNull(process.env.REACT_APP_COLLECT_PROJECT_VERSION, "3.20.1-SNAPSHOT")
static BASE_URL = Constants.determineBaseURL();
static BASE_ASSETS_URL = Constants.determineBaseAssetsURL();
static API_BASE_URL = Constants.BASE_URL + "api/";
static determineBaseURL() {
if (Constants.isDevReact()) {
return "http://127.0.0.1:8080/collect/";
} else {
let l = window.location;
return l.origin + l.pathname;
}
}
static determineBaseAssetsURL() {
let l = window.location;
return l.origin + l.pathname + 'assets/';
}
static isDevReact() {
return typeof JSON3 !== 'undefined' //TODO improve it
}
}
|
import Objects from 'utils/Objects'
export default class Constants {
static APP_VERSION = Objects.defaultIfNull(process.env.REACT_APP_COLLECT_PROJECT_VERSION, "3.14.0-SNAPSHOT")
static BASE_URL = Constants.determineBaseURL();
static BASE_ASSETS_URL = Constants.determineBaseAssetsURL();
static API_BASE_URL = Constants.BASE_URL + "api/";
static determineBaseURL() {
if (Constants.isDevReact()) {
return "http://127.0.0.1:8080/collect/";
} else {
let l = window.location;
return l.origin + l.pathname;
}
}
static determineBaseAssetsURL() {
let l = window.location;
return l.origin + l.pathname + 'assets/';
}
static isDevReact() {
return typeof JSON3 !== 'undefined' //TODO improve it
}
}
|
Change order of imports to fix install into blank db or as dependency of
company config.
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Trading As Brands
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import (
res_company_brand,
res_partner,
res_company,
)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Trading As Brands
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import (
res_company_brand,
res_company,
res_partner,
)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
Refactor earth mover's distance implementation
|
import collections
def each(function, iterable):
for item in iterable:
function(item)
def each_unpack(function, iterable):
for item in iterable:
function(*item)
def minmax(*args):
min = None
max = None
for x in args:
if max < x:
max = x
if x > min:
min = x
return min, max
def map_inplace(function, list, depth=0):
if depth <= 0:
list[:] = map(function, list)
else:
for item in list:
map_inplace(function, item, depth - 1)
def count_if(function, iterable):
count = 0
for item in iterable:
if function(item):
count += 1
return count
def teemap(iterable, *functions):
map(lambda item: (f(item) for f in functions), iterable)
class ProbabilityDistribution(collections.defaultdict):
""""Holds a probability distribution and can compute the distance to other dists"""
def __init__(self):
collections.defaultdict.__init__(self, int)
def get(self, k, d = 0):
return dict.get(self, k, d)
def distance_to(self, compare_to):
return sum(
(abs(self.get(bin) - compare_to.get(bin))
for bin in self.viewkeys() | compare_to.viewkeys()),
0)
|
import collections
def each(function, iterable):
for item in iterable:
function(item)
def each_unpack(function, iterable):
for item in iterable:
function(*item)
def minmax(*args):
min = None
max = None
for x in args:
if max < x:
max = x
if x > min:
min = x
return min, max
def map_inplace(function, list, depth=0):
if depth <= 0:
list[:] = map(function, list)
else:
for item in list:
map_inplace(function, item, depth - 1)
def count_if(function, iterable):
count = 0
for item in iterable:
if function(item):
count += 1
return count
def teemap(iterable, *functions):
map(lambda item: (f(item) for f in functions), iterable)
class ProbabilityDistribution(collections.defaultdict):
""""Holds a probability distribution and can compute the distance to other dists"""
def __init__(self):
collections.defaultdict.__init__(self, int)
def get(self, k, d = 0):
return dict.get(self, k, d)
def distance_to(self, compare_to):
key_set = self.viewkeys() | compare_to.viewkeys()
currentEMD = 0
lastEMD = 0
totaldistance = 0
for key in key_set:
lastEMD = currentEMD
currentEMD = (self.get(key, 0) + lastEMD) - compare_to.get(key, 0)
totaldistance += math.fabs(currentEMD)
return totaldistance
|
Replace argument name window -> exports
|
(function (exports) {
'use strict';
var HearingTest = Object.create(null);
var context = new window.AudioContext();
HearingTest.init = function init(frequency) {
frequency = frequency || 440;
var sound = this.createSound();
sound.frequency.value = frequency;
this.connect(sound);
this.sound = sound;
return sound;
};
HearingTest.createSound = function createSound() {
return context.createOscillator();
};
HearingTest.connect = function connect(sound) {
return sound.connect(context.destination);
};
HearingTest.playSound = function playSound(delay) {
delay = delay || 0;
this.sound.start(delay);
};
HearingTest.stopSound = function stopSound(delay) {
delay = delay || 0;
this.sound.stop(delay);
};
exports.HearingTest = HearingTest;
}(window));
|
(function (window) {
'use strict';
var HearingTest = Object.create(null);
var context = new window.AudioContext();
HearingTest.init = function init(frequency) {
frequency = frequency || 440;
var sound = this.createSound();
sound.frequency.value = frequency;
this.connect(sound);
this.sound = sound;
return sound;
};
HearingTest.createSound = function createSound() {
return context.createOscillator();
};
HearingTest.connect = function connect(sound) {
return sound.connect(context.destination);
};
HearingTest.playSound = function playSound(delay) {
delay = delay || 0;
this.sound.start(delay);
};
HearingTest.stopSound = function stopSound(delay) {
delay = delay || 0;
this.sound.stop(delay);
};
window.HearingTest = HearingTest;
}(window));
|
Simplify by making root element initially an array
|
'use strict';
var xmlWrite = require('./xmlWrite');
function traverse(obj,parent,attributePrefix) {
var result = [];
var array = Array.isArray(obj);
for (var key in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(key)) continue;
var propArray = Array.isArray(obj[key]);
var output = array ? parent : key;
if (typeof obj[key] !== 'object'){
if (key.indexOf(attributePrefix)==0) {
xmlWrite.attribute(key.substring(1),obj[key]);
}
else {
xmlWrite.startElement(output);
xmlWrite.content(obj[key]);
xmlWrite.endElement(output);
}
}
else {
if (!propArray) {
xmlWrite.startElement(output);
}
traverse(obj[key],output,attributePrefix);
if (!propArray) {
xmlWrite.endElement(output);
}
}
}
return result;
}
module.exports = {
getXml : function(obj,attrPrefix,standalone,indent,indentStr,fragment) {
var attributePrefix = (attrPrefix ? attrPrefix : '@');
if (fragment) {
xmlWrite.startFragment(indent,indentStr);
}
else {
xmlWrite.startDocument('UTF-8',standalone,indent,indentStr);
}
traverse(obj,'',attributePrefix);
return xmlWrite.endDocument();
}
};
|
'use strict';
var xmlWrite = require('./xmlWrite');
var attributePrefix = '@';
function traverse(obj,parent) {
var result = [];
var array = Array.isArray(obj);
for (var key in obj) {
// skip loop if the property is from prototype
if (!obj.hasOwnProperty(key)) continue;
var propArray = Array.isArray(obj[key]);
var output = array ? parent : key;
if (typeof obj[key] !== 'object'){
if (key.indexOf(attributePrefix)==0) {
xmlWrite.attribute(key.substring(1),obj[key]);
}
else {
xmlWrite.startElement(output);
xmlWrite.content(obj[key]);
xmlWrite.endElement(output);
}
}
else {
if (!propArray) {
xmlWrite.startElement(output);
}
traverse(obj[key],output);
if (!propArray) {
xmlWrite.endElement(output);
}
}
}
return result;
}
module.exports = {
getXml : function(obj,attrPrefix,standalone,indent,indentStr,fragment) {
if (attrPrefix) attributePrefix = attrPrefix;
if (fragment) {
xmlWrite.startFragment(indent,indentStr);
}
else {
xmlWrite.startDocument('UTF-8',standalone,indent,indentStr);
}
traverse(obj,'');
return xmlWrite.endDocument();
}
};
|
Reduce elevator chance to 1 in 10 again
|
import React from 'react';
import { ReactComponent as Logo } from 'interface/images/logo.svg';
// This has an elevator music easter egg that occurs randomly once every 5 times.
// Lazy load it to minimize bundle impact. This whole joke has a tiny amount of overhead.
let elevator;
async function loadElevator() {
elevator = (await import('./elevate')).default;
}
let useElevator = Math.random() < 0.1;
function scrollToTop() {
if (!useElevator || !elevator) {
window.scrollTo(0, 0);
} else {
elevator();
// Only do it once to increase ~~confusion~~ mystery
useElevator = false;
}
}
const ScrollToTop = () => (
<div className="clickable text-right" onClick={scrollToTop} onMouseEnter={useElevator ? loadElevator : undefined}>
<Logo
style={{ '--arrow': '#fab700', '--main': '#1c1c1b', maxWidth: 50 }}
/>
</div>
);
export default ScrollToTop;
|
import React from 'react';
import { ReactComponent as Logo } from 'interface/images/logo.svg';
// This has an elevator music easter egg that occurs randomly once every 5 times.
// Lazy load it to minimize bundle impact. This whole joke has a tiny amount of overhead.
let elevator;
async function loadElevator() {
elevator = (await import('./elevate')).default;
}
let useElevator = Math.random() < 0.2;
function scrollToTop() {
if (!useElevator || !elevator) {
window.scrollTo(0, 0);
} else {
elevator();
// Only do it once to increase ~~confusion~~ mystery
useElevator = false;
}
}
const ScrollToTop = () => (
<div className="clickable text-right" onClick={scrollToTop} onMouseEnter={useElevator ? loadElevator : undefined}>
<Logo
style={{ '--arrow': '#fab700', '--main': '#1c1c1b', maxWidth: 50 }}
/>
</div>
);
export default ScrollToTop;
|
Increase refresh time for download list
|
'use strict';
/**
* @ngdoc function
* @name torrentSubscribeFrontendApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the torrentSubscribeFrontendApp
*/
angular.module('torrentSubscribeFrontendApp')
.controller('ClientCtrl', ['$scope', '$timeout', 'TorrentClient', function ($scope, $timeout, TorrentClient) {
$scope.filterTerm = "";
$scope.torrents = [];
$scope.getClientTorrents = function() {
TorrentClient.getAll(function(result) {
$scope.torrents = [];
Object.keys(result).forEach(function(key) {
$scope.torrents.push(result[key]);
});
$timeout($scope.getClientTorrents, 10000);
});
};
$scope.getClientTorrents();
}]);
|
'use strict';
/**
* @ngdoc function
* @name torrentSubscribeFrontendApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the torrentSubscribeFrontendApp
*/
angular.module('torrentSubscribeFrontendApp')
.controller('ClientCtrl', ['$scope', '$timeout', 'TorrentClient', function ($scope, $timeout, TorrentClient) {
$scope.filterTerm = "";
$scope.torrents = [];
$scope.getClientTorrents = function() {
TorrentClient.getAll(function(result) {
$scope.torrents = [];
Object.keys(result).forEach(function(key) {
$scope.torrents.push(result[key]);
});
$timeout($scope.getClientTorrents, 1000);
});
};
$scope.getClientTorrents();
}]);
|
cliedit: Rename the functions in history: to be backward compatible.
|
package cliedit
import (
"github.com/elves/elvish/cli"
"github.com/elves/elvish/cli/addons/histwalk"
"github.com/elves/elvish/cli/el"
"github.com/elves/elvish/cli/histutil"
"github.com/elves/elvish/eval"
)
func initHistWalk(app *cli.App, ev *eval.Evaler, ns eval.Ns, fuser *histutil.Fuser) {
bindingVar := newBindingVar(emptyBindingMap)
binding := newMapBinding(app, ev, bindingVar)
ns.AddNs("history",
eval.Ns{
"binding": bindingVar,
}.AddGoFns("<edit:history>", map[string]interface{}{
"start": func() { histWalkStart(app, fuser, binding) },
"up": func() error { return histwalk.Prev(app) },
"down": func() error { return histwalk.Next(app) },
"close": func() { histwalk.Close(app) },
}))
}
func histWalkStart(app *cli.App, fuser *histutil.Fuser, binding el.Handler) {
buf := app.CodeArea.CopyState().CodeBuffer
walker := fuser.Walker(buf.Content[:buf.Dot])
histwalk.Start(app, histwalk.Config{Binding: binding, Walker: walker})
}
|
package cliedit
import (
"github.com/elves/elvish/cli"
"github.com/elves/elvish/cli/addons/histwalk"
"github.com/elves/elvish/cli/histutil"
"github.com/elves/elvish/eval"
)
func initHistWalk(app *cli.App, ev *eval.Evaler, ns eval.Ns, fuser *histutil.Fuser) {
bindingVar := newBindingVar(emptyBindingMap)
binding := newMapBinding(app, ev, bindingVar)
ns.AddNs("history",
eval.Ns{
"binding": bindingVar,
}.AddGoFns("<edit:history>", map[string]interface{}{
"start": func() {
buf := app.CodeArea.CopyState().CodeBuffer
walker := fuser.Walker(buf.Content[:buf.Dot])
histwalk.Start(app, histwalk.Config{Binding: binding, Walker: walker})
},
"prev": func() error { return histwalk.Prev(app) },
"next": func() error { return histwalk.Next(app) },
"close": func() { histwalk.Close(app) },
}))
}
|
Fix selector for startpage controller test
|
<?php
namespace Tests\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class StartpageControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$client->request('GET', '/');
$this->assertTrue(
$client->getResponse()->isRedirect('/test/startpage'),
'response is a redirect to /test/startpage'
);
$crawler = $client->followRedirect();
$this->assertEquals(200, $client->getResponse()->getStatusCode());
$this->assertContains('Projects', $crawler->filter('#wrapper')->text());
$this->assertContains('Organisms', $crawler->filter('#wrapper')->text());
$this->assertContains('Traits', $crawler->filter('#wrapper')->text());
}
}
|
<?php
namespace Tests\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class StartpageControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/');
$this->assertTrue(
$client->getResponse()->isRedirect('/test/startpage'),
'response is a redirect to /test/startpage'
);
$crawler = $client->followRedirect();
$this->assertEquals(200, $client->getResponse()->getStatusCode());
$this->assertContains('Projects', $crawler->filter('div')->text());
$this->assertContains('Organisms', $crawler->filter('div')->text());
$this->assertContains('Traits', $crawler->filter('div')->text());
}
}
|
Cut out logo in README uploaded to PyPi
|
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as readme:
README = readme.read().split('h1>', 2)[1]
setup(
name='django-postgres-extra',
version='1.21a2',
packages=find_packages(),
include_package_data=True,
license='MIT License',
description='Bringing all of PostgreSQL\'s awesomeness to Django.',
long_description=README,
url='https://github.com/SectorLabs/django-postgres-extra',
author='Sector Labs',
author_email='open-source@sectorlabs.ro',
keywords=['django', 'postgres', 'extra', 'hstore', 'ltree'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
]
)
|
import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as readme:
README = readme.read()
setup(
name='django-postgres-extra',
version='1.21a2',
packages=find_packages(),
include_package_data=True,
license='MIT License',
description='Bringing all of PostgreSQL\'s awesomeness to Django.',
long_description=README,
url='https://github.com/SectorLabs/django-postgres-extra',
author='Sector Labs',
author_email='open-source@sectorlabs.ro',
keywords=['django', 'postgres', 'extra', 'hstore', 'ltree'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
]
)
|
Fix closing of OrientDB in test case
|
package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseType;
import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.db.OrientDBConfig;
import org.junit.AfterClass;
import org.junit.BeforeClass;
/**
* Created by olena.kolesnyk on 28/07/2017.
*/
public class CreateMemoryDatabaseFixture {
protected static ODatabase database;
protected static OrientDB factory;
private static final String PATH = "memory";
private static final String DB_NAME = "test_database";
private static final String USER = "admin";
private static final String PASSWORD = "admin";
@BeforeClass
public static void setUp() {
factory = new OrientDB(PATH, OrientDBConfig.defaultConfig());
factory.create(DB_NAME, ODatabaseType.MEMORY);
database = factory.open(DB_NAME, USER, PASSWORD);
}
@AfterClass
public static void tearDown() {
database.close();
factory.drop(DB_NAME);
factory.close();
}
}
|
package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseType;
import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.db.OrientDBConfig;
import org.junit.AfterClass;
import org.junit.BeforeClass;
/**
* Created by olena.kolesnyk on 28/07/2017.
*/
public class CreateMemoryDatabaseFixture {
protected static ODatabase database;
protected static OrientDB factory;
private static final String PATH = "memory";
private static final String DB_NAME = "test_database";
private static final String USER = "admin";
private static final String PASSWORD = "admin";
@BeforeClass
public static void setUp() {
factory = new OrientDB(PATH, OrientDBConfig.defaultConfig());
factory.create(DB_NAME, ODatabaseType.MEMORY);
database = factory.open(DB_NAME, USER, PASSWORD);
}
@AfterClass
public static void tearDown() {
database.close();
factory.drop(DB_NAME);
}
}
|
Fix relocation of hash information on startup of cluster interface
|
/*jslint indent: 2, nomen: true, maxlen: 100, white: true, */
/*global window, $, Backbone, document */
(function() {
"use strict";
$.get("cluster/amIDispatcher", function(data) {
if (!data) {
var url = window.location.origin;
url += window.location.pathname;
url = url.replace("cluster", "index");
window.location.replace(url);
}
});
window.location.hash = "";
$(document).ready(function() {
window.App = new window.ClusterRouter();
Backbone.history.start();
if(window.App.clusterPlan.get("plan")) {
if(window.App.clusterPlan.isAlive()) {
window.App.showCluster();
} else {
window.App.handleClusterDown();
}
} else {
window.App.planScenario();
}
window.App.handleResize();
});
}());
|
/*jslint indent: 2, nomen: true, maxlen: 100, white: true, */
/*global window, $, Backbone, document */
(function() {
"use strict";
$.get("cluster/amIDispatcher", function(data) {
if (!data) {
var url = window.location.origin;
url += window.location.pathname;
url = url.replace("cluster", "index");
window.location.replace(url);
}
});
$(document).ready(function() {
window.App = new window.ClusterRouter();
Backbone.history.start();
window.App.navigate("", {trigger: true});
if(window.App.clusterPlan.get("plan")) {
if(window.App.clusterPlan.isAlive()) {
window.App.showCluster();
} else {
window.App.handleClusterDown();
}
} else {
window.App.planScenario();
}
window.App.handleResize();
});
}());
|
Use production dashboard API endpoint
|
import click
import requests
from shub.utils import find_api_key
from shub.click_utils import log
@click.command(help="Download a project's eggs from the Scrapy Cloud")
@click.argument("project_id", required=True)
def cli(project_id):
auth = (find_api_key(), '')
url = "https://dash.scrapinghub.com/api/eggs/bundle.zip?project=%s" % project_id
rsp = requests.get(url=url, auth=auth, stream=True, timeout=300)
destfile = 'eggs-%s.zip' % project_id
log("Downloading eggs to %s" % destfile)
with open(destfile, 'wb') as f:
for chunk in rsp.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
f.flush()
|
import click
import requests
from shub.utils import find_api_key
from shub.click_utils import log
@click.command(help="Download a project's eggs from the Scrapy Cloud")
@click.argument("project_id", required=True)
def cli(project_id):
auth = (find_api_key(), '')
url = "https://staging.scrapinghub.com/api/eggs/bundle.zip?project=%s" % project_id
rsp = requests.get(url=url, auth=auth, stream=True, timeout=300)
destfile = 'eggs-%s.zip' % project_id
log("Downloading eggs to %s" % destfile)
with open(destfile, 'wb') as f:
for chunk in rsp.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
f.flush()
|
Throw an error instead of killing the process
|
var fs = require ('fs');
var logger = {
_logFile: undefined,
initLog: function (logfile_, version_) {
logger._logFile = logfile_;
// Clear the log
fs.writeFileSync (logger._logFile, "");
// Write header data
fs.appendFileSync (logger._logFile,
'Created with ugly v' + version_);
fs.appendFileSync (logger._logFile,
'Start date: ' + (new Date ().toString ()));
fs.appendFileSync (logger._logFile,
'=================================================');
},
// Print an info (non-fatal) message to the console and the log file
info: function (msg_) {
var time = new Date ().getTime ();
msg_ = '[' + time + '] INFO: ' + msg_;
console.log (msg_);
fs.appendFileSync (logger._logFile, msg_);
},
// Print an error (fatal) message to the consol and the log file and then
// kill the program
error: function (msg_) {
var time = new Date ().getTime ();
var logMsg = '[' + time + '] ERROR: ' + msg_;
fs.appendFileSync (logger._logFile, logMsg);
throw new Error (msg_);
}
};
module.exports = logger;
|
var fs = require ('fs');
var logger = {
_logFile: undefined,
initLog: function (logfile_, version_) {
logger._logFile = logfile_;
// Clear the log
fs.writeFileSync (logger._logFile, "");
// Write header data
fs.appendFileSync (logger._logFile,
'Created with ugly v' + version_);
fs.appendFileSync (logger._logFile,
'Start date: ' + (new Date ().toString ()));
fs.appendFileSync (logger._logFile,
'=================================================');
},
// Print an info (non-fatal) message to the console and the log file
info: function (msg_) {
var time = new Date ().getTime ();
msg_ = '[' + time + '] INFO: ' + msg_;
console.log (msg_);
fs.appendFileSync (logger._logFile, msg_);
},
// Print an error (fatal) message to the consol and the log file and then
// kill the program
error: function (msg_) {
var time = new Date ().getTime ();
msg_ = '[' + time + '] ERROR: ' + msg_;
console.error (msg_);
fs.appendFileSync (logger._logFile, msg_);
process.exit (1);
}
};
module.exports = logger;
|
Add italic javadoc goodness (review comments by Cowan)
|
package com.custardsource.parfait.dxm;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Builds a ByteBuffer in memory, mostly useful for unit testing purposes
*/
public class InMemoryByteBufferFactory implements ByteBufferFactory{
private ByteBuffer byteBuffer;
private int numAllocations;
@Override
public ByteBuffer build(int length) throws IOException {
byteBuffer = ByteBuffer.allocate(length);
numAllocations++;
return byteBuffer;
}
/**
* Returns the <em>last</em> allocated ByteBuffer used during creation, so that further inspection can be done during unit tests.
*
* You are reminded that this class may be used multiple times, this reference is only the last one created
*/
public ByteBuffer getAllocatedBuffer() {
return byteBuffer;
}
/**
* Returns the # ByteBuffer allocations that have occured, since this Factory may produce more than one in its
* life
*/
public int getNumAllocations() {
return numAllocations;
}
}
|
package com.custardsource.parfait.dxm;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Builds a ByteBuffer in memory, mostly useful for unit testing purposes
*/
public class InMemoryByteBufferFactory implements ByteBufferFactory{
private ByteBuffer byteBuffer;
private int numAllocations;
@Override
public ByteBuffer build(int length) throws IOException {
byteBuffer = ByteBuffer.allocate(length);
numAllocations++;
return byteBuffer;
}
/**
* Returns the _last_ allocated ByteBuffer used during creation, so that further inspection can be done during unit tests.
*
* You are reminded that this class may be used multiple times, this reference is only the last one created
*/
public ByteBuffer getAllocatedBuffer() {
return byteBuffer;
}
/**
* Returns the # ByteBuffer allocations that have occured, since this Factory may produce more than one in its
* life
*/
public int getNumAllocations() {
return numAllocations;
}
}
|
Allow ring buffer to refer to underlying (drained) queue's index
|
package net.openhft.chronicle.bytes;
import java.io.Closeable;
public interface RingBufferReader extends RingBufferReaderStats, Closeable {
boolean isEmpty();
boolean isClosed();
/**
* Close the reader. After being closed, the reader will not block writers
*/
@Override
void close();
/**
* the readPosition and readLimit will be adjusted so that the client can read the data
*
* @param bytes who's byteStore must be the ring buffer,
* @return nextReadPosition which should be passed to {@link RingBufferReader#afterRead(long)}
*/
@SuppressWarnings("rawtypes")
long beforeRead(Bytes bytes);
void afterRead(long next);
void afterRead(long next, long underlyingIndex);
/**
* Convenience method calls both {@link #beforeRead(Bytes)} and {@link #afterRead(long)}
* @param bytes
* @return whether read succeeded
*/
@SuppressWarnings("rawtypes")
boolean read(BytesOut bytes);
/**
* @return the byteStore which backs the ring buffer
*/
@SuppressWarnings("rawtypes")
BytesStore byteStore();
/**
* Take reader to just past the end of the RB
*/
void toEnd();
}
|
package net.openhft.chronicle.bytes;
import java.io.Closeable;
public interface RingBufferReader extends RingBufferReaderStats, Closeable {
boolean isEmpty();
boolean isClosed();
/**
* Close the reader. After being closed, the reader will not block writers
*/
@Override
void close();
/**
* the readPosition and readLimit will be adjusted so that the client can read the data
*
* @param bytes who's byteStore must be the ring buffer,
* @return nextReadPosition which should be passed to {@link RingBufferReader#afterRead(long)}
*/
@SuppressWarnings("rawtypes")
long beforeRead(Bytes bytes);
void afterRead(long next);
/**
* Convenience method calls both {@link #beforeRead(Bytes)} and {@link #afterRead(long)}
* @param bytes
* @return whether read succeeded
*/
@SuppressWarnings("rawtypes")
boolean read(BytesOut bytes);
/**
* @return the byteStore which backs the ring buffer
*/
@SuppressWarnings("rawtypes")
BytesStore byteStore();
/**
* Take reader to just past the end of the RB
*/
void toEnd();
}
|
Change conditional for macos pyobjc usage
macOS 11.x will occasionally identify as 10.16, since there was no real
reason to prevent on all supported platforms allow.
|
# Copyright 2017 Virgil Dupras
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
from platform import mac_ver
from sys import version_info
# NOTE: version of pyobjc only supports python >= 3.6 and 10.9+
macos_ver = tuple(int(part) for part in mac_ver()[0].split("."))
if version_info >= (3, 6) and macos_ver >= (10, 9):
try:
from .plat_osx_pyobjc import send2trash
except ImportError:
# Try to fall back to ctypes version, although likely problematic still
from .plat_osx_ctypes import send2trash
else:
# Just use the old version otherwise
from .plat_osx_ctypes import send2trash # noqa: F401
|
# Copyright 2017 Virgil Dupras
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
from platform import mac_ver
from sys import version_info
# If macOS is 11.0 or newer try to use the pyobjc version to get around #51
# NOTE: pyobjc only supports python >= 3.6
if version_info >= (3, 6) and int(mac_ver()[0].split(".", 1)[0]) >= 11:
try:
from .plat_osx_pyobjc import send2trash
except ImportError:
# Try to fall back to ctypes version, although likely problematic still
from .plat_osx_ctypes import send2trash
else:
# Just use the old version otherwise
from .plat_osx_ctypes import send2trash # noqa: F401
|
Raise exception when --debug is specified to main script
I.e., instead of printing the exception and then exiting.
|
import sys
from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer
def main(argv=None):
debug = None
try:
all_argv, run_argv, command_argv = partition_argv(argv)
cli_args = run.parse_args(RawConfig(run=RunConfig()), run_argv)
run_args = read_run_args(run)
run_args.update(cli_args)
debug = run_args.get('debug', run.parameters['debug'].default)
run.implementation(
None, all_argv=all_argv, run_argv=run_argv, command_argv=command_argv,
cli_args=cli_args, **run_args)
except RunCommandsError as exc:
if debug or debug is None:
# User specified --debug OR processing didn't get far enough
# to determine whether user specified --debug.
raise
printer.error(exc, file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
|
import sys
from .config import RawConfig, RunConfig
from .exc import RunCommandsError
from .run import run, partition_argv, read_run_args
from .util import printer
def main(argv=None):
try:
all_argv, run_argv, command_argv = partition_argv(argv)
cli_args = run.parse_args(RawConfig(run=RunConfig()), run_argv)
run_args = read_run_args(run)
run_args.update(cli_args)
run.implementation(
None, all_argv=all_argv, run_argv=run_argv, command_argv=command_argv,
cli_args=cli_args, **run_args)
except RunCommandsError as exc:
printer.error(exc, file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())
|
Fix swapped king and queen
|
package matrix
import "point"
type Matrix [8][8]byte
var starting = Matrix{
{'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'},
{'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
{'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'},
}
func Starting() Matrix {
return starting
}
func InMatrix(p point.Point) bool {
return 0 <= p.X && p.X < 8 && 0 <= p.Y && p.Y < 8
}
func (mat Matrix) ExistBarrier(from, to point.Point) bool {
p := from
p.StepTo(to)
for p != to {
if mat[p.Y][p.X] != ' ' {
return true
}
p.StepTo(to)
}
return false
}
|
package matrix
import "point"
type Matrix [8][8]byte
var starting = Matrix{
{'r', 'n', 'b', 'k', 'q', 'b', 'n', 'r'},
{'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
{'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
{'R', 'N', 'B', 'K', 'Q', 'B', 'N', 'R'},
}
func Starting() Matrix {
return starting
}
func InMatrix(p point.Point) bool {
return 0 <= p.X && p.X < 8 && 0 <= p.Y && p.Y < 8
}
func (mat Matrix) ExistBarrier(from, to point.Point) bool {
p := from
p.StepTo(to)
for p != to {
if mat[p.Y][p.X] != ' ' {
return true
}
p.StepTo(to)
}
return false
}
|
Fix bug in command parser
|
define([], function() {
var CommandParser = (function() {
var parse = function(str, lookForQuotes) {
var args = [];
var readingPart = false;
var part = '';
for(var i=0; i < str.length; i++) {
if(str.charAt(i) === ' ' && !readingPart) {
args.push(part);
part = '';
} else {
if(str.charAt(i) === '\"' && lookForQuotes) {
readingPart = !readingPart;
} else {
part += str.charAt(i);
}
}
}
args.push(part);
return args;
}
return {
parse: parse
}
})();
return CommandParser
})
|
define([], function() {
var CommandParser = (function() {
var parse = function(str, lookForQuotes) {
var args = [];
var readingPart = false;
var part = '';
for(var i=0; i < str.length; i++) {
if(str.charAt(i) === ' ' && !readingPart) {
args.push(part);
part = '';
} else {
if(str.charAt(i) === '\"' === "'" && lookForQuotes) {
readingPart = !readingPart;
} else {
part += str.charAt(i);
}
}
}
args.push(part);
return args;
}
return {
parse: parse
}
})();
return CommandParser
})
|
Allow _job_manager special object to be overriden by task if desired
|
import imp
import json
import sys
def run(task, inputs, outputs, task_inputs, task_outputs, **kwargs):
custom = imp.new_module("custom")
custom.__dict__['_job_manager'] = kwargs.get('_job_manager')
for name in inputs:
custom.__dict__[name] = inputs[name]["script_data"]
try:
exec task["script"] in custom.__dict__
except Exception, e:
trace = sys.exc_info()[2]
lines = task["script"].split("\n")
lines = [(str(i+1) + ": " + lines[i]) for i in xrange(len(lines))]
error = (
str(e) + "\nScript:\n" + "\n".join(lines) +
"\nTask:\n" + json.dumps(task, indent=4)
)
raise Exception(error), None, trace
for name, task_output in task_outputs.iteritems():
outputs[name]["script_data"] = custom.__dict__[name]
|
import imp
import json
import sys
def run(task, inputs, outputs, task_inputs, task_outputs, **kwargs):
custom = imp.new_module("custom")
for name in inputs:
custom.__dict__[name] = inputs[name]["script_data"]
custom.__dict__['_job_manager'] = kwargs.get('_job_manager')
try:
exec task["script"] in custom.__dict__
except Exception, e:
trace = sys.exc_info()[2]
lines = task["script"].split("\n")
lines = [(str(i+1) + ": " + lines[i]) for i in xrange(len(lines))]
error = (
str(e) + "\nScript:\n" + "\n".join(lines) +
"\nTask:\n" + json.dumps(task, indent=4)
)
raise Exception(error), None, trace
for name, task_output in task_outputs.iteritems():
outputs[name]["script_data"] = custom.__dict__[name]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.