text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Set Postgres autocommit as supported only if server version is < 7.4
The server-side autocommit setting was removed here http://www.postgresql.org/docs/7.4/static/release-7-4.html
Resolves: #690 | import psycopg2
from airflow.hooks.dbapi_hook import DbApiHook
class PostgresHook(DbApiHook):
'''
Interact with Postgres.
You can specify ssl parameters in the extra field of your connection
as ``{"sslmode": "require", "sslcert": "/path/to/cert.pem", etc}``.
'''
conn_name_attr = 'postgres_conn_id'
default_conn_name = 'postgres_default'
supports_autocommit = False
def get_conn(self):
conn = self.get_connection(self.postgres_conn_id)
conn_args = dict(
host=conn.host,
user=conn.login,
password=conn.password,
dbname=conn.schema,
port=conn.port)
# check for ssl parameters in conn.extra
for arg_name, arg_val in conn.extra_dejson.items():
if arg_name in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']:
conn_args[arg_name] = arg_val
psycopg2_conn = psycopg2.connect(**conn_args)
if psycopg2_conn.server_version < 70400:
self.supports_autocommit = True
return psycopg2_conn
| import psycopg2
from airflow.hooks.dbapi_hook import DbApiHook
class PostgresHook(DbApiHook):
'''
Interact with Postgres.
You can specify ssl parameters in the extra field of your connection
as ``{"sslmode": "require", "sslcert": "/path/to/cert.pem", etc}``.
'''
conn_name_attr = 'postgres_conn_id'
default_conn_name = 'postgres_default'
supports_autocommit = True
def get_conn(self):
conn = self.get_connection(self.postgres_conn_id)
conn_args = dict(
host=conn.host,
user=conn.login,
password=conn.password,
dbname=conn.schema,
port=conn.port)
# check for ssl parameters in conn.extra
for arg_name, arg_val in conn.extra_dejson.items():
if arg_name in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']:
conn_args[arg_name] = arg_val
return psycopg2.connect(**conn_args)
|
Remove drop for index that wasnt created. | <?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20181220212723 extends AbstractMigration
{
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE ls_doc ADD frameworktype_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE ls_doc ADD CONSTRAINT FK_9AE8CF1F3C4C17B2 FOREIGN KEY (frameworktype_id) REFERENCES ls_def_framework_type (id)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE ls_doc DROP frameworktype_id');
}
}
| <?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20181220212723 extends AbstractMigration
{
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE ls_doc ADD frameworktype_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE ls_doc ADD CONSTRAINT FK_9AE8CF1F3C4C17B2 FOREIGN KEY (frameworktype_id) REFERENCES ls_def_framework_type (id)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('DROP INDEX IDX_9AE8CF1F3C4C17B2 ON ls_doc');
$this->addSql('ALTER TABLE ls_doc DROP frameworktype_id');
}
}
|
Use turbolinks event handler instead of document ready. | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require react
//= require react_ujs
//= require components
//= require_tree .
var update = React.addons.update
$(document).on('turbolinks:load', function() {
var timezone = jstz.determine()
cookies({timezone: timezone.name()})
$('.ratingCircle').click(function(e) {
console.log($(this).find('.ratingNumber').text())
$('.ratingCircle').removeClass('active')
$(this).addClass('active')
$('#ratingInput').val($(this).find('.ratingNumber').text())
})
var removeFlash = function() {
$('.flash').fadeOut()
}
setTimeout(removeFlash, 5000)
})
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require react
//= require react_ujs
//= require components
//= require_tree .
var update = React.addons.update
$(function() {
var timezone = jstz.determine()
cookies({timezone: timezone.name()})
$('.ratingCircle').click(function(e) {
console.log($(this).find('.ratingNumber').text())
$('.ratingCircle').removeClass('active')
$(this).addClass('active')
$('#ratingInput').val($(this).find('.ratingNumber').text())
})
var removeFlash = function() {
$('.flash').fadeOut()
}
setTimeout(removeFlash, 5000)
})
|
Add supplier/ prefix to static file paths | import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
STATIC_URL_PATH = '/supplier/static'
ASSET_PATH = STATIC_URL_PATH + '/'
BASE_TEMPLATE_DATA = {
'asset_path': ASSET_PATH,
'header_class': 'with-proposition'
}
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
class Live(Config):
DEBUG = False
config = {
'live': Live,
'development': Development,
'test': Test,
'default': Development
}
| import os
import jinja2
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
@staticmethod
def init_app(app):
repo_root = os.path.abspath(os.path.dirname(__file__))
template_folders = [
os.path.join(repo_root,
'bower_components/govuk_template/views/layouts'),
os.path.join(repo_root, 'app/templates')
]
jinja_loader = jinja2.FileSystemLoader(template_folders)
app.jinja_loader = jinja_loader
class Test(Config):
DEBUG = True
class Development(Config):
DEBUG = True,
BASE_TEMPLATE_DATA = {
'asset_path': '/static/',
'header_class': 'with-proposition'
}
class Live(Config):
DEBUG = False
config = {
'live': Live,
'development': Development,
'test': Test,
'default': Development
}
|
Print json to console if a table isn't suitable.
Also remove redundant comment. | /**
* The sitespeed.io coach (https://www.sitespeed.io/coach)
* Copyright (c) 2016, Peter Hedenskog, Tobias Lidskog
* and other contributors
* Released under the Apache 2.0 License
*/
'use strict';
let path = require('path'),
fs = require('fs');
module.exports = function(filename) {
let coachSrc = fs.readFileSync(path.join(__dirname, '../../dist/','coach.js'));
const combinedSrc = `(function() {
var result = ${coachSrc}
Object.keys(result).forEach(function(key) {
if (result[key].adviceList) {
console.log(key);
console.table(result[key].adviceList, ['score','advice']);
}
else {
console.log(key + ': ' + JSON.stringify(result[key], null, 2));
}
});
})();
`;
fs.writeFileSync(filename, combinedSrc);
};
| /**
* The sitespeed.io coach (https://www.sitespeed.io/coach)
* Copyright (c) 2016, Peter Hedenskog, Tobias Lidskog
* and other contributors
* Released under the Apache 2.0 License
*/
'use strict';
let path = require('path'),
fs = require('fs');
module.exports = function(filename) {
let coachSrc = fs.readFileSync(path.join(__dirname, '../../dist/','coach.js'));
const combinedSrc = `(function() {
var result = ${coachSrc}
Object.keys(result).forEach(function(key) {
// do we have advices?
if (result[key].adviceList) {
console.log(key);
console.table(result[key].adviceList, ['score','advice']);
}
else {
console.log(key + ': ' + result[key]);
}
});
})();
`;
fs.writeFileSync(filename, combinedSrc);
};
|
Enable chrome://inspect on debug builds | package net.elprespufferfish.rssreader;
import android.app.Application;
import android.os.Build;
import android.os.StrictMode;
import android.webkit.WebView;
public class RssReaderApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Feeds.initialize();
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
}
}
}
| package net.elprespufferfish.rssreader;
import android.app.Application;
import android.os.StrictMode;
public class RssReaderApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Feeds.initialize();
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build());
}
}
}
|
Add ice rinks to used services | import {Schema} from 'normalizr';
import {normalizeActionName} from '../common/helpers';
export const UnitServices = {
MECHANICALLY_FROZEN_ICE: 33417,
ICE_SKATING_FIELD: 33418,
ICE_RINK: 33419,
SPEED_SKATING_TRACK: 33420,
SKI_TRACK: 33483,
DOG_SKI_TRACK: 33492
};
export const IceSkatingServices = [
UnitServices.MECHANICALLY_FROZEN_ICE,
UnitServices.ICE_SKATING_FIELD,
UnitServices.ICE_RINK,
UnitServices.SPEED_SKATING_TRACK
];
export const SkiingServices = [
UnitServices.SKI_TRACK,
UnitServices.DOG_SKI_TRACK
];
export const SwimmingServices = [];
export const ServiceActions = {
FETCH: normalizeActionName('service/FETCH'),
RECEIVE: normalizeActionName('service/RECEIVE'),
FETCH_ERROR: normalizeActionName('service/FETCH_ERROR')
};
export type UnitState = {
isFetching: boolean,
byId: Object,
// Filtered arrays of ids
all: Array<string>,
skating: Array<string>,
skiing: Array<string>,
searchResults: Array<string>
};
export const serviceSchema = new Schema('service'/*, {}*/);
| import {Schema} from 'normalizr';
import {normalizeActionName} from '../common/helpers';
export const UnitServices = {
MECHANICALLY_FROZEN_ICE: 33417,
ICE_SKATING_FIELD: 33418,
SPEED_SKATING_TRACK: 33420,
SKI_TRACK: 33483,
DOG_SKI_TRACK: 33492
};
export const IceSkatingServices = [
UnitServices.MECHANICALLY_FROZEN_ICE,
UnitServices.ICE_SKATING_FIELD,
UnitServices.SPEED_SKATING_TRACK
];
export const SkiingServices = [
UnitServices.SKI_TRACK,
UnitServices.DOG_SKI_TRACK
];
export const SwimmingServices = [];
export const ServiceActions = {
FETCH: normalizeActionName('service/FETCH'),
RECEIVE: normalizeActionName('service/RECEIVE'),
FETCH_ERROR: normalizeActionName('service/FETCH_ERROR')
};
export type UnitState = {
isFetching: boolean,
byId: Object,
// Filtered arrays of ids
all: Array<string>,
skating: Array<string>,
skiing: Array<string>,
searchResults: Array<string>
};
export const serviceSchema = new Schema('service'/*, {}*/);
|
Remove references to old-name _Gagger_ in the sample. | package coffee;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import javax.inject.Inject;
import sheath.Modules;
import sheath.SheathEntryPoint;
class CoffeeApp implements EntryPoint {
@Modules(DripCoffeeModule.class)
interface CoffeeGraph extends SheathEntryPoint<CoffeeApp> { }
@Inject CoffeeMaker coffeeMaker;
@Override
public void onModuleLoad() {
CoffeeGraph graph = GWT.create(CoffeeGraph.class);
graph.inject(this);
Button btn = Button.wrap(Document.get().getElementById("coffeeMaker"));
btn.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
coffeeMaker.brew();
}
});
btn.setEnabled(true);
}
}
| package coffee;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import javax.inject.Inject;
import sheath.Modules;
import sheath.SheathEntryPoint;
class CoffeeApp implements EntryPoint {
@Modules(DripCoffeeModule.class)
interface CoffeeGagger extends SheathEntryPoint<CoffeeApp> { }
@Inject CoffeeMaker coffeeMaker;
@Override
public void onModuleLoad() {
CoffeeGagger gagger = GWT.create(CoffeeGagger.class);
gagger.inject(this);
Button btn = Button.wrap(Document.get().getElementById("coffeeMaker"));
btn.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
coffeeMaker.brew();
}
});
btn.setEnabled(true);
}
}
|
Add missing newline at end of file | var ZIP = require("./zip");
var FS = require("fs");
var assert = require("assert");
console.log("-------------------");
console.log("READ from Buffer");
var data = FS.readFileSync("zip.zip")
var reader = ZIP.Reader(data);
var readFromBuffer = reader.toObject('utf-8');
console.log(readFromBuffer);
reader.forEach(function (entry) {
console.log(entry.getName(), entry.lastModified(), entry.getMode());
});
console.log("-------------------");
console.log("READ from file descriptor");
FS.open("zip.zip", "r", "0666", function(err, fd) {
var reader = ZIP.Reader(fd);
var readFromFileDescriptor = reader.toObject('utf-8');
console.log(readFromFileDescriptor);
assert.deepEqual(readFromBuffer, readFromFileDescriptor, 'READ from Buffer MUST be equal to READ from file descriptor');
});
| var ZIP = require("./zip");
var FS = require("fs");
var assert = require("assert");
console.log("-------------------");
console.log("READ from Buffer");
var data = FS.readFileSync("zip.zip")
var reader = ZIP.Reader(data);
var readFromBuffer = reader.toObject('utf-8');
console.log(readFromBuffer);
reader.forEach(function (entry) {
console.log(entry.getName(), entry.lastModified(), entry.getMode());
});
console.log("-------------------");
console.log("READ from file descriptor");
FS.open("zip.zip", "r", "0666", function(err, fd) {
var reader = ZIP.Reader(fd);
var readFromFileDescriptor = reader.toObject('utf-8');
console.log(readFromFileDescriptor);
assert.deepEqual(readFromBuffer, readFromFileDescriptor, 'READ from Buffer MUST be equal to READ from file descriptor');
}); |
Remove iFrame sandbox from Modernizr | /*
* MODERNIZR: Modernizr builder
*/
module.exports = {
/*
* TARGET: Build custom Modernizr
*/
prepare: {
devFile: 'remote',
outputFile: '<%= path.tmp %>/modernizr-custom.js',
extra: {
touch: true,
shiv: true,
cssclasses: true,
load: false
},
extensibility: {
teststyles: true,
prefixes: true
},
tests: [
'cookies'
],
uglify: false,
matchCommunityTests: true,
parseFiles: false
}
};
| /*
* MODERNIZR: Modernizr builder
*/
module.exports = {
/*
* TARGET: Build custom Modernizr
*/
prepare: {
devFile: 'remote',
outputFile: '<%= path.tmp %>/modernizr-custom.js',
extra: {
touch: true,
shiv: true,
cssclasses: true,
load: false
},
extensibility: {
teststyles: true,
prefixes: true
},
tests: [
'cookies',
'iframe-sandbox'
],
uglify: false,
matchCommunityTests: true,
parseFiles: false
}
};
|
Reorder property to keep XWiki order | var props = require("../properties/all.js");
var BaseObj = require("../BaseObj");
var obj = BaseObj.create("XWiki.StyleSheetExtension");
obj.addProp("cache", props.StaticList.create({
"prettyName": "Caching policy",
"values": "long|short|default|forbid"
}));
obj.addProp("code", props.TextArea.create({
"prettyName": "Code"
}));
obj.addProp("name", props.XString.create({
"prettyName": "Name",
"size": "30"
}));
obj.addProp("parse", props.XBoolean.create({
"prettyName": "Parse content"
}));
obj.addProp("use", props.StaticList.create({
"prettyName": "Use this extension",
"values": "currentPage=Always on this page|onDemand=On demand|always=Always on this wiki"
}));
module.exports.create = function () {
return obj.instance();
};
| var props = require("../properties/all.js");
var BaseObj = require("../BaseObj");
var obj = BaseObj.create("XWiki.StyleSheetExtension");
obj.addProp("name", props.XString.create({
"prettyName": "Name",
"size": "30"
}));
obj.addProp("code", props.TextArea.create({
"prettyName": "Code"
}));
obj.addProp("use", props.StaticList.create({
"prettyName": "Use this extension",
"values": "currentPage=Always on this page|onDemand=On demand|always=Always on this wiki"
}));
obj.addProp("parse", props.XBoolean.create({
"prettyName": "Parse content"
}));
obj.addProp("cache", props.StaticList.create({
"prettyName": "Caching policy",
"values": "long|short|default|forbid"
}));
module.exports.create = function () {
return obj.instance();
};
|
Add upload file size limit | from __future__ import print_function
import os
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
UPLOAD_FOLDER = '/app/input'
ALLOWED_EXTENSIONS = set(['txt','xls','xlsx','csv','tsv','md'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 100*1024*1024 #set max upload file size to 100mb
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET','POST'])
def upload_file():
if request.method == 'POST':
file = request.files['files']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('upload_file', filename=filename))
return render_template('index.html')
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_form_directory(app.config['UPLOAD_FOLDER'])
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5050))
app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True) | from __future__ import print_function
import os
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
UPLOAD_FOLDER = '/app/input'
ALLOWED_EXTENSIONS = set(['txt','xls','xlsx','csv','tsv','md'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET','POST'])
def upload_file():
if request.method == 'POST':
file = request.files['files']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('upload_file', filename=filename))
return render_template('index.html')
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_form_directory(app.config['UPLOAD_FOLDER'])
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5050))
app.run(host='0.0.0.0', port=port, debug=True, use_reloader=True) |
Reset current store when an exception is caught | <?php
class Meanbee_ConfigPoweredCss_Adminhtml_ConfigPoweredCssController extends Mage_Adminhtml_Controller_Action
{
public function regenerateAction()
{
/** @var Mage_Adminhtml_Model_Session $session */
$session = Mage::getSingleton('adminhtml/session');
/** @var Meanbee_ConfigPoweredCss_Model_Css $css */
$css = Mage::getModel('meanbee_configpoweredcss/css');
$stores = Mage::app()->getStores();
foreach ($stores as $storeId => $store) {
try {
Mage::app()->setCurrentStore($storeId);
$css->publish($storeId);
} catch (Exception $e) {
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$session->addError($e->getMessage());
$this->_redirect('*/cache');
return;
}
}
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$session->addSuccess("Successfully regenerated CSS file(s)");
$this->_redirect('*/cache');
}
}
| <?php
class Meanbee_ConfigPoweredCss_Adminhtml_ConfigPoweredCssController extends Mage_Adminhtml_Controller_Action
{
public function regenerateAction()
{
/** @var Mage_Adminhtml_Model_Session $session */
$session = Mage::getSingleton('adminhtml/session');
/** @var Meanbee_ConfigPoweredCss_Model_Css $css */
$css = Mage::getModel('meanbee_configpoweredcss/css');
$stores = Mage::app()->getStores();
foreach ($stores as $storeId => $store) {
try {
Mage::app()->setCurrentStore($storeId);
$css->publish($storeId);
} catch (Exception $e) {
$session->addError($e->getMessage());
$this->_redirect('*/cache');
return;
}
}
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$session->addSuccess("Successfully regenerated CSS file(s)");
$this->_redirect('*/cache');
}
}
|
Call MPIOutput.file.Sync() in MPIOutput.file._write() to prevent log lines from intermittently being lost. | #!/usr/bin/env python
"""
MPI utilities.
"""
from mpi4py import MPI
import twiggy
class MPIOutput(twiggy.outputs.Output):
"""
Output messages to a file via MPI I/O.
"""
def __init__(self, name, format, comm,
mode=MPI.MODE_CREATE | MPI.MODE_WRONLY,
close_atexit=True):
self.filename = name
self._format = format if format is not None else self._noop_format
self.comm = comm
self.mode = mode
super(MPIOutput, self).__init__(format, close_atexit)
def _open(self):
self.file = MPI.File.Open(self.comm, self.filename,
self.mode)
def _close(self):
self.file.Close()
def _write(self, x):
self.file.Iwrite_shared(x)
# This seems to be necessary to prevent some log lines from being lost:
self.file.Sync()
| #!/usr/bin/env python
"""
MPI utilities.
"""
from mpi4py import MPI
import twiggy
class MPIOutput(twiggy.outputs.Output):
"""
Output messages to a file via MPI I/O.
"""
def __init__(self, name, format, comm,
mode=MPI.MODE_CREATE | MPI.MODE_WRONLY,
close_atexit=True):
self.filename = name
self._format = format if format is not None else self._noop_format
self.comm = comm
self.mode = mode
super(MPIOutput, self).__init__(format, close_atexit)
def _open(self):
self.file = MPI.File.Open(self.comm, self.filename,
self.mode)
def _close(self):
self.file.Close()
def _write(self, x):
self.file.Iwrite_shared(x)
|
Remove initialiser for removed lightbox
This lightbox was used on people pages where the role had more than one
associated organisation. We are no longer showing these as a list, but
as a sentence at the bottom of the role so this can go | // Happen as soon as the DOM is loaded and before assets are downloaded
jQuery(function($) {
$('.js-hide-other-links').hideOtherLinks();
$('.js-hide-other-departments').hideOtherLinks({ linkElement: 'span', alwaysVisibleClass: '.lead' });
$('.govspeak').enhanceYoutubeVideoLinks();
GOVUK.stickAtTopWhenScrolling.init();
$('.js-toggle-change-notes').toggler({actLikeLightbox: true});
$('.js-toggle-footer-change-notes').toggler();
$('.js-toggle-accessibility-warning').toggler({header: ".toggler", content: ".help-block"})
$(".js-document-filter").enableDocumentFilter();
$('.js-hide-extra-social-media').hideExtraRows({ rows: 5 });
$('.js-hide-extra-metadata').hideExtraRows({ rows: 2, appendToParent: true });
$('.see-all-updates').click(function(e) {
GOVUK.stickAtTopWhenScrolling.stick($('.js-stick-at-top-when-scrolling'));
$('#history .overlay').removeClass('visuallyhidden');
});
GOVUK.hideDepartmentChildren.init();
GOVUK.filterListItems.init();
GOVUK.showHide.init();
GOVUK.virtualTour.init();
GOVUK.feeds.init();
});
// These want images to be loaded before they run so the page height doesn't change.
jQuery(window).load(function(){
GOVUK.backToContent.init();
});
| // Happen as soon as the DOM is loaded and before assets are downloaded
jQuery(function($) {
$('.js-hide-other-links').hideOtherLinks();
$('.js-hide-other-departments').hideOtherLinks({ linkElement: 'span', alwaysVisibleClass: '.lead' });
$('.govspeak').enhanceYoutubeVideoLinks();
GOVUK.stickAtTopWhenScrolling.init();
$('.js-toggle-change-notes').toggler({actLikeLightbox: true});
$('.js-toggle-footer-change-notes').toggler();
$('.js-toggle-accessibility-warning').toggler({header: ".toggler", content: ".help-block"})
$('.js-toggle-org-list').toggler({actLikeLightbox: true})
$(".js-document-filter").enableDocumentFilter();
$('.js-hide-extra-social-media').hideExtraRows({ rows: 5 });
$('.js-hide-extra-metadata').hideExtraRows({ rows: 2, appendToParent: true });
$('.see-all-updates').click(function(e) {
GOVUK.stickAtTopWhenScrolling.stick($('.js-stick-at-top-when-scrolling'));
$('#history .overlay').removeClass('visuallyhidden');
});
GOVUK.hideDepartmentChildren.init();
GOVUK.filterListItems.init();
GOVUK.showHide.init();
GOVUK.virtualTour.init();
GOVUK.feeds.init();
});
// These want images to be loaded before they run so the page height doesn't change.
jQuery(window).load(function(){
GOVUK.backToContent.init();
});
|
Add test to check failed status return failed | <?php
namespace Maenbn\Tests\GitlabCiBuildStatus;
use Maenbn\GitlabCiBuildStatus\Client;
class ClientTest extends \PHPUnit_Framework_TestCase
{
public function testStatusReturnsString()
{
$client = new Client('https://gitlab.com/api/v3', 1031075, getenv('GITLAB_PRIVATE_KEY'));
$status = $client->getStatus();
$this->assertTrue(is_string($status));
}
public function testFailedStatusReturnsString()
{
$client = new Client('https://gitlab.com/api/v3', 1031075, getenv('GITLAB_PRIVATE_KEY'));
$status = $client->getStatus('failing');
$this->assertTrue(is_string($status));
}
/**
* @expectedException \Exception
* @expectedExceptionMessageRegExp #Error:.*#
*
*/
public function testCurlExceptionThrown(){
$client = new Client('https://somerandomciwhichiswrong.com/ci', 1, 'somerandomwrongtoken');
$client->getStatus();
}
}
| <?php
namespace Maenbn\Tests\GitlabCiBuildStatus;
use Maenbn\GitlabCiBuildStatus\Client;
class ClientTest extends \PHPUnit_Framework_TestCase
{
public function testStatusReturnsString()
{
$client = new Client('https://gitlab.com/api/v3', 1031075, getenv('GITLAB_PRIVATE_KEY'));
$status = $client->getStatus();
$this->assertTrue(is_string($status));
}
/**
* @expectedException \Exception
* @expectedExceptionMessageRegExp #Error:.*#
*
*/
public function testCurlExceptionThrown(){
$client = new Client('https://somerandomciwhichiswrong.com/ci', 1, 'somerandomwrongtoken');
$client->getStatus();
}
}
|
Add a failure expectation to Linux memory.css3d test.
BUG=373098
NOTRY=true
R=kbr@chromium.org
Review URL: https://codereview.chromium.org/303503009
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@273109 0039d316-1c4b-4281-b951-d872f2087c98 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
# TODO(vmpstr): Memory drops and increases again, and this
# particular bot happens to catch it when its low. Remove
# once the bug is fixed.
self.Fail('Memory.CSS3D', ['win'], bug=373098)
# Test has turned flaky on Linux also. Remove once the bug is fixed.
self.Fail('Memory.CSS3D', ['linux'], bug=373098)
| # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
# TODO(vmpstr): Memory drops and increases again, and this
# particular bot happens to catch it when its low. Remove
# once the bug is fixed.
self.Fail('Memory.CSS3D', ['win'], bug=373098)
|
Change names to not include `Bot`.
The invocation in client code will include the twitterbot prefix,
so including Bot in the name is redundant. Calls now look like
`t := twitterbot.New(config)`. | package twitterbot
import (
"fmt"
"time"
"github.com/ChimeraCoder/anaconda"
)
type TBot struct {
api *anaconda.TwitterApi
keys *Keys
}
func New(config string) (*TBot, error) {
keys, err := ReadConfig(config)
if err != nil {
return nil, err
}
anaconda.SetConsumerKey(keys.consumerPublic)
anaconda.SetConsumerSecret(keys.consumerSecret)
api := anaconda.NewTwitterApi(keys.accessPublic, keys.accessSecret)
return &TBot{api, keys}, nil
}
type TweetCreator interface {
NextTweet() string
}
func (t *TBot) Run(creator TweetCreator) {
var previousTweet string
for {
tweet := creator.NextTweet()
if previousTweet == "" || previousTweet != tweet {
fmt.Println("[" + time.Now().Format(time.RFC850) + "] Posting " + tweet)
t.api.PostTweet(tweet, nil)
previousTweet = tweet
}
fmt.Println("[" + time.Now().Format(time.RFC850) + "] Sleeping...")
time.Sleep(10 * time.Minute)
}
}
| package twitterbot
import (
"fmt"
"time"
"github.com/ChimeraCoder/anaconda"
)
type TBot struct {
api *anaconda.TwitterApi
keys *Keys
}
func NewBot(config string) (*TBot, error) {
keys, err := ReadConfig(config)
if err != nil {
return nil, err
}
anaconda.SetConsumerKey(keys.consumerPublic)
anaconda.SetConsumerSecret(keys.consumerSecret)
api := anaconda.NewTwitterApi(keys.accessPublic, keys.accessSecret)
return &TBot{api, keys}, nil
}
type TweetCreator interface {
NextTweet() string
}
func (t *TBot) RunBot(creator TweetCreator) {
var previousTweet string
for {
tweet := creator.NextTweet()
if previousTweet == "" || previousTweet != tweet {
fmt.Println("[" + time.Now().Format(time.RFC850) + "] Posting " + tweet)
t.api.PostTweet(tweet, nil)
previousTweet = tweet
}
fmt.Println("[" + time.Now().Format(time.RFC850) + "] Sleeping...")
time.Sleep(10 * time.Minute)
}
}
|
Check the x-forwarded-proto header before redirecting to HTTPS (again) | var configuration = require("configvention"),
urlUtil = require("url"),
redirectRequestToHttps = function(req, res) {
var secureRoot = configuration.get("https-url-root"),
secureUrl = urlUtil.resolve(secureRoot, req.originalUrl);
// From https://github.com/aredo/express-enforces-ssl
if (req.method === "GET") {
res.redirect(301, secureUrl);
} else {
res.send(403, "Please use HTTPS when submitting data to this server.");
}
},
configuredHttpsRedirect = function() {
var middleware = function(req, res, next) {
if (req.headers["x-forwarded-proto"] !== "https" && configuration.get("redirect-to-https") === true) {
redirectRequestToHttps(req, res);
} else {
next();
}
};
return middleware;
};
module.exports = configuredHttpsRedirect; | var configuration = require("configvention"),
urlUtil = require("url"),
redirectRequestToHttps = function(req, res) {
var secureRoot = configuration.get("https-url-root"),
secureUrl = urlUtil.resolve(secureRoot, req.originalUrl);
// From https://github.com/aredo/express-enforces-ssl
if (req.method === "GET") {
res.redirect(301, secureUrl);
} else {
res.send(403, "Please use HTTPS when submitting data to this server.");
}
},
configuredHttpsRedirect = function() {
var middleware = function(req, res, next) {
if (req.secure !== true && configuration.get("redirect-to-https") === true) {
redirectRequestToHttps(req, res);
} else {
next();
}
};
return middleware;
};
module.exports = configuredHttpsRedirect; |
Return proper response if redis is not available | <?php
namespace Alcohol\PasteBundle\EventListener;
use Predis\Connection\ConnectionException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
class ExceptionListener
{
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$response = new Response($exception->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
if ($exception instanceof ConnectionException) {
$exception = new ServiceUnavailableHttpException(300, $exception->getMessage(), $exception);
$event->setException($exception);
}
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
}
$event->setResponse($response);
}
}
| <?php
namespace Alcohol\PasteBundle\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class ExceptionListener
{
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$response = new Response($exception->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
}
$event->setResponse($response);
}
}
|
SimonStewart: Make the selenium-backed webdriver emulate the normal webdriver's xpath mode
git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@10674 07704840-8298-11de-bf8c-fd130f914ac9 | /*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 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 org.openqa.selenium.internal.selenesedriver;
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import java.util.HashMap;
import java.util.Map;
public class NewSession implements SeleneseFunction<Map<String, Object>> {
public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) {
selenium.start();
// Emulate behaviour of webdriver
selenium.useXpathLibrary("javascript-xpath");
selenium.allowNativeXpath("true");
Capabilities capabilities = (Capabilities) args.get("desiredCapabilities");
Map<String, Object> seenCapabilities = new HashMap<String, Object>();
seenCapabilities.put("browserName", capabilities.getBrowserName());
seenCapabilities.put("version", capabilities.getVersion());
seenCapabilities.put("platform", Platform.getCurrent().toString());
seenCapabilities.put("javascriptEnabled", true);
return seenCapabilities;
}
}
| /*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 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 org.openqa.selenium.internal.selenesedriver;
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import java.util.HashMap;
import java.util.Map;
public class NewSession implements SeleneseFunction<Map<String, Object>> {
public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) {
selenium.start();
Capabilities capabilities = (Capabilities) args.get("desiredCapabilities");
Map<String, Object> seenCapabilities = new HashMap<String, Object>();
seenCapabilities.put("browserName", capabilities.getBrowserName());
seenCapabilities.put("version", capabilities.getVersion());
seenCapabilities.put("platform", Platform.getCurrent().toString());
seenCapabilities.put("javascriptEnabled", true);
return seenCapabilities;
}
}
|
Test that attrs are passed to 'mesh' DataArray | """Unit tests for the pymt.framwork.bmi_ugrid module."""
import xarray as xr
from pymt.framework.bmi_ugrid import Scalar, Vector
from pymt.framework.bmi_bridge import _BmiCap
grid_id = 0
class TestScalar:
def get_grid_rank(self, grid_id):
return 0
class ScalarBmi(_BmiCap):
_cls = TestScalar
def test_scalar_grid():
"""Testing creating a scalar grid."""
bmi = ScalarBmi()
grid = Scalar(bmi, grid_id)
assert grid.ndim == 0
assert grid.metadata["type"] == "scalar"
assert grid.data_vars["mesh"].attrs["type"] == "scalar"
assert isinstance(grid, xr.Dataset)
class TestVector:
def get_grid_rank(self, grid_id):
return 1
class VectorBmi(_BmiCap):
_cls = TestVector
def test_vector_grid():
"""Testing creating a vector grid."""
bmi = VectorBmi()
grid = Vector(bmi, grid_id)
assert grid.ndim == 1
assert grid.metadata["type"] == "vector"
assert grid.data_vars["mesh"].attrs["type"] == "vector"
assert isinstance(grid, xr.Dataset)
| """Unit tests for the pymt.framwork.bmi_ugrid module."""
import xarray as xr
from pymt.framework.bmi_ugrid import Scalar, Vector
from pymt.framework.bmi_bridge import _BmiCap
grid_id = 0
class TestScalar:
def get_grid_rank(self, grid_id):
return 0
class ScalarBmi(_BmiCap):
_cls = TestScalar
def test_scalar_grid():
"""Testing creating a scalar grid."""
bmi = ScalarBmi()
grid = Scalar(bmi, grid_id)
assert grid.ndim == 0
assert grid.metadata["type"] == "scalar"
assert isinstance(grid, xr.Dataset)
class TestVector:
def get_grid_rank(self, grid_id):
return 1
class VectorBmi(_BmiCap):
_cls = TestVector
def test_vector_grid():
"""Testing creating a vector grid."""
bmi = VectorBmi()
grid = Vector(bmi, grid_id)
assert grid.ndim == 1
assert grid.metadata["type"] == "vector"
assert isinstance(grid, xr.Dataset)
|
Send weekly report to aws | # coding=utf-8
import logging
from django.core.management.base import BaseCommand
from reports.tasks import ExportTask
from core.models import get_web_user
from django.views.decorators.csrf import csrf_exempt
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "This runs the MCCB1sSLA report"
def handle(self, *args, **options):
self.create_report()
@csrf_exempt
def create_report(self):
report_data = '{"action": "Export", "csrfmiddlewaretoken": "PQk4Pt55CL0NBapx9hSqZTJkSn6tL6TL", "date_from": "2021-05-08", "date_to": "2021-05-10"}'
# report_data = json_stuff_goes_here
web_user = get_web_user()
filename_of_report = "WEEKLY-REPORT-TEST.csv"
ExportTask().delay(web_user.pk, filename_of_report, "MICB1Extract", report_data)
| # coding=utf-8
import logging
from django.core.management.base import BaseCommand
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "This runs the MCCB1sSLA report"
def handle(self, *args, **options):
self.create_report()
def create_report():
print("stuff goes here")
# '{"action": "Export", "csrfmiddlewaretoken": "PQk4Pt55CL0NBapx9hSqZTJkSn6tL6TL", "date_from": "08/05/2021", "date_to": "10/05/2021"}'
# report_data = json_stuff_goes_here
# ExportTask().delay(user_person.pk, filename_of_report, mi_cb1_extract_agilisys, report_data)
|
Revert "Tweak log formating to append colon and space to stdout type."
This reverts commit 246fdaece68ae60c6f25fa59f27d9c4183371b9b. | var Logger = function (config) {
this.config = config;
this.backend = this.config.backend || 'stdout'
this.level = this.config.level || "LOG_INFO"
if (this.backend == 'stdout') {
this.util = require('util');
} else {
if (this.backend == 'syslog') {
this.util = require('node-syslog');
this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0);
} else {
throw "Logger: Should be 'stdout' or 'syslog'."
}
}
}
Logger.prototype = {
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
type = 'DEBUG: ';
}
this.util.log(type + msg);
} else {
if (!type) {
type = this.level
if (!this.util[type]) {
throw "Undefined log level: " + type;
}
} else if (type == 'debug') {
type = "LOG_DEBUG";
}
this.util.log(this.util[type], msg);
}
}
}
exports.Logger = Logger
| var Logger = function (config) {
this.config = config;
this.backend = this.config.backend || 'stdout'
this.level = this.config.level || "LOG_INFO"
if (this.backend == 'stdout') {
this.util = require('util');
} else {
if (this.backend == 'syslog') {
this.util = require('node-syslog');
this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0);
} else {
throw "Logger: Should be 'stdout' or 'syslog'."
}
}
}
Logger.prototype = {
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
type = 'DEBUG';
}
this.util.log(type + ": " + msg);
} else {
if (!type) {
type = this.level
if (!this.util[type]) {
throw "Undefined log level: " + type;
}
} else if (type == 'debug') {
type = "LOG_DEBUG";
}
this.util.log(this.util[type], msg);
}
}
}
exports.Logger = Logger
|
Fix name space in the service provider. | <?php
namespace Spatie\LaravelSlack;
use Illuminate\Support\ServiceProvider;
use Spatie\LaravelSlack\SlashCommandHandler\Collection;
use Spatie\LaravelSlack\SlashCommandRequest;
class LaravelSlackServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot()
{
$this->publishes([
__DIR__.'/../config/laravel-slack.php' => config_path('laravel-slack.php'),
], 'config');
$this->app['router']->get(config('laravel-slack.slash_command_url'), function () {
$slashCommandRequest = SlashCommandRequest::createForRequest(request());
$slashCommandHandlers = new Collection(config('laravel-slack.slash_command_handlers'), $slashCommandRequest);
return $slashCommandHandlers->getResponse();
});
}
/**
* Register the application services.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/laravel-slack.php', 'laravel-slack');
}
}
| <?php
namespace Spatie\Skeleton;
use Illuminate\Support\ServiceProvider;
use Spatie\LaravelSlack\SlashCommandHandler\Collection;
use Spatie\LaravelSlack\SlashCommandRequest;
class LaravelSlackServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot()
{
$this->publishes([
__DIR__.'/../config/laravel-slack.php' => config_path('laravel-slack.php'),
], 'config');
$this->app['router']->get(config('laravel-slack.slash_command_url'), function () {
$slashCommandRequest = SlashCommandRequest::createForRequest(request());
$slashCommandHandlers = new Collection(config('laravel-slack.slash_command_handlers'), $slashCommandRequest);
return $slashCommandHandlers->getResponse();
});
}
/**
* Register the application services.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/laravel-slack.php', 'laravel-slack');
}
}
|
Check for spaces being ignored in inline versions | import static org.junit.jupiter.api.Assertions.assertEquals;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.Version;
import java.util.Set;
import org.junit.jupiter.api.Test;
class ModulesParseTextBlockDeclarationTest {
@Test
void parseDeclaration() {
var descriptor = Bach.Modules.parseDeclaration("""
module foo.bar {
requires foo.bax;
requires foo.bay/*1*/;
requires foo.baz /* 2.3-ea */;
}
""");
assertEquals("foo.bar", descriptor.name(), descriptor.toString());
assertEquals(
ModuleDescriptor.newModule("x")
.requires("foo.bax")
.requires(Set.of(), "foo.bay", Version.parse("1"))
.requires(Set.of(), "foo.baz", Version.parse("2.3-ea"))
.build()
.requires(),
descriptor.requires(),
descriptor.toString());
}
}
| import static org.junit.jupiter.api.Assertions.assertEquals;
import java.lang.module.ModuleDescriptor;
import java.util.Set;
import org.junit.jupiter.api.Test;
class ModulesParseTextBlockDeclarationTest {
@Test
void parseDeclaration() {
var descriptor = Bach.Modules.parseDeclaration("""
module foo.bar { // 3.3-ALPHA
requires foo.bax; // @1.3
requires foo.bay/*342*/;
requires foo.baz; // 47.11
}
""");
assertEquals("foo.bar", descriptor.name(), descriptor.toString());
assertEquals(
ModuleDescriptor.newModule("x")
.requires("foo.bax")
.requires(Set.of(), "foo.bay", ModuleDescriptor.Version.parse("342"))
.requires("foo.baz")
.build()
.requires(),
descriptor.requires(),
descriptor.toString());
}
}
|
Revise Collection comments to be more clear/correct | 'use strict';
// A general container for any ordered sequence of items
function Collection(SubCollectionItem, itemDicts) {
var collection = this;
// A reference to the constructor for the sub-collection's item type
collection.SubCollectionItem = SubCollectionItem;
collection.items = itemDicts.map(function (itemDict) {
return new SubCollectionItem(itemDict);
});
}
Collection.prototype.get = function (itemIndex) {
return this.items[itemIndex];
};
Collection.prototype.insert = function (itemIndex, itemDict) {
// This method will automatically convert the given property map into the
// correct item type for the sub-collection instance
return this.items.splice(itemIndex, 0, new this.SubCollectionItem(itemDict));
};
Collection.prototype.remove = function (itemIndex) {
return this.items.splice(itemIndex, 1);
};
Collection.prototype.forEach = function (callback) {
return this.items.forEach(callback);
};
Collection.prototype.filter = function (callback) {
return this.items.filter(callback);
};
Collection.prototype.map = function (callback) {
return this.items.map(callback);
};
// Define an array-like 'length' property on Collection instances
Object.defineProperty(Collection.prototype, 'length', {
enumerable: false,
configurable: false,
get: function () {
return this.items.length;
},
set: function (newLength) {
this.items.length = newLength;
return newLength;
}
});
module.exports = Collection;
| 'use strict';
// A general container for any type of collection
function Collection(SubCollectionItem, itemDicts) {
var collection = this;
// A reference to the sub-collection's item constructor
collection.SubCollectionItem = SubCollectionItem;
collection.items = itemDicts.map(function (itemDict) {
return new SubCollectionItem(itemDict);
});
}
// Retrieve the collection item at the given index
Collection.prototype.get = function (itemIndex) {
return this.items[itemIndex];
};
// Insert the given collection item dictionary at the given index
Collection.prototype.insert = function (itemIndex, itemDict) {
return this.items.splice(itemIndex, 0, new this.SubCollectionItem(itemDict));
};
Collection.prototype.remove = function (itemIndex) {
return this.items.splice(itemIndex, 1);
};
Collection.prototype.forEach = function (callback) {
return this.items.forEach(callback);
};
Collection.prototype.filter = function (callback) {
return this.items.filter(callback);
};
Collection.prototype.map = function (callback) {
return this.items.map(callback);
};
// Define an array-like 'length' property on Collection instances
Object.defineProperty(Collection.prototype, 'length', {
enumerable: false,
configurable: false,
get: function () {
return this.items.length;
},
set: function (newLength) {
this.items.length = newLength;
return newLength;
}
});
module.exports = Collection;
|
Add leading slash to `JsonSerializable` on docblock
Co-Authored-By: rodrigopedra <9ab0a48cbad7071f1c06b52d0c74cf226c5339e9@gmail.com> | <?php
namespace Illuminate\Http\Resources;
use JsonSerializable;
use Illuminate\Support\Collection;
class MergeValue
{
/**
* The data to be merged.
*
* @var array
*/
public $data;
/**
* Create new merge value instance.
*
* @param \Illuminate\Support\Collection|\JsonSerializable|array $data
* @return void
*/
public function __construct($data)
{
if ($data instanceof Collection) {
$this->data = $data->all();
} elseif ($data instanceof JsonSerializable) {
$this->data = $data->jsonSerialize();
} else {
$this->data = $data;
}
}
}
| <?php
namespace Illuminate\Http\Resources;
use JsonSerializable;
use Illuminate\Support\Collection;
class MergeValue
{
/**
* The data to be merged.
*
* @var array
*/
public $data;
/**
* Create new merge value instance.
*
* @param \Illuminate\Support\Collection|JsonSerializable|array $data
* @return void
*/
public function __construct($data)
{
if ($data instanceof Collection) {
$this->data = $data->all();
} elseif ($data instanceof JsonSerializable) {
$this->data = $data->jsonSerialize();
} else {
$this->data = $data;
}
}
}
|
Add a fourth graph annotation style which highlights optional segments in blue.
git-svn-id: a0d2519504059b70a86a1ce51b726c2279190bad@25234 6e01202a-0783-4428-890a-84243c50cc2b | package org.concord.datagraph.analysis;
import java.awt.Component;
import java.util.ArrayList;
import org.concord.data.state.OTDataStore;
import org.concord.datagraph.analysis.rubric.GraphRubric;
import org.concord.datagraph.analysis.rubric.ResultSet;
import org.concord.datagraph.state.OTDataCollector;
import org.concord.datagraph.state.OTDataGraphable;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.graph.util.state.OTHideableAnnotation;
public interface GraphAnalyzer {
public enum AnnotationStyle { ONE, TWO, THREE, FOUR }
public Graph getSegments(OTDataStore dataStore, int xChannel, int yChannel, double tolerance) throws IndexOutOfBoundsException;
public GraphRubric buildRubric(OTObjectList rubric);
public ResultSet compareGraphs(GraphRubric expected, Graph received);
public String getHtmlReasons(ResultSet results);
public void displayHtmlReasonsPopup(Component parent, ResultSet results);
public ArrayList<OTHideableAnnotation> annotateResults(OTDataCollector dataCollector, ResultSet scoreResults, AnnotationStyle style);
public ArrayList<OTDataGraphable> drawSegmentResults(OTDataCollector dataCollector, Graph graph);
}
| package org.concord.datagraph.analysis;
import java.awt.Component;
import java.util.ArrayList;
import org.concord.data.state.OTDataStore;
import org.concord.datagraph.analysis.rubric.GraphRubric;
import org.concord.datagraph.analysis.rubric.ResultSet;
import org.concord.datagraph.state.OTDataCollector;
import org.concord.datagraph.state.OTDataGraphable;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.graph.util.state.OTHideableAnnotation;
public interface GraphAnalyzer {
public enum AnnotationStyle { ONE, TWO, THREE }
public Graph getSegments(OTDataStore dataStore, int xChannel, int yChannel, double tolerance) throws IndexOutOfBoundsException;
public GraphRubric buildRubric(OTObjectList rubric);
public ResultSet compareGraphs(GraphRubric expected, Graph received);
public String getHtmlReasons(ResultSet results);
public void displayHtmlReasonsPopup(Component parent, ResultSet results);
public ArrayList<OTHideableAnnotation> annotateResults(OTDataCollector dataCollector, ResultSet scoreResults, AnnotationStyle style);
public ArrayList<OTDataGraphable> drawSegmentResults(OTDataCollector dataCollector, Graph graph);
}
|
Stop "Header" fields (labels for form sections) from trying to generate Conduit edits
Summary: Fixes T12236. Headers are currently trying to generate an edit transaction for `maniphest.edit` and similar, but should not, since you can't edit them.
Test Plan:
- Configured Maniphest with a custom header field.
- Before change: `maniphest.edit` API console page fataled.
- After change: all good, no weird "header" transaction.
- Header still shows up on "Edit Task" form in web UI.
Reviewers: chad
Reviewed By: chad
Maniphest Tasks: T12236
Differential Revision: https://secure.phabricator.com/D17332 | <?php
final class PhabricatorStandardCustomFieldHeader
extends PhabricatorStandardCustomField {
public function getFieldType() {
return 'header';
}
public function renderEditControl(array $handles) {
$header = phutil_tag(
'div',
array(
'class' => 'phabricator-standard-custom-field-header',
),
$this->getFieldName());
return id(new AphrontFormStaticControl())
->setValue($header);
}
public function shouldUseStorage() {
return false;
}
public function getStyleForPropertyView() {
return 'header';
}
public function renderPropertyViewValue(array $handles) {
return $this->getFieldName();
}
public function shouldAppearInApplicationSearch() {
return false;
}
public function shouldAppearInConduitTransactions() {
return false;
}
}
| <?php
final class PhabricatorStandardCustomFieldHeader
extends PhabricatorStandardCustomField {
public function getFieldType() {
return 'header';
}
public function renderEditControl(array $handles) {
$header = phutil_tag(
'div',
array(
'class' => 'phabricator-standard-custom-field-header',
),
$this->getFieldName());
return id(new AphrontFormStaticControl())
->setValue($header);
}
public function shouldUseStorage() {
return false;
}
public function getStyleForPropertyView() {
return 'header';
}
public function renderPropertyViewValue(array $handles) {
return $this->getFieldName();
}
public function shouldAppearInApplicationSearch() {
return false;
}
}
|
FIX Use localhost as default URL | var config = {};
config.thinkingThings = {
logLevel: 'ERROR',
port: 8000,
root: '/thinkingthings',
sleepTime: 300
};
config.ngsi = {
logLevel: 'ERROR',
defaultType: 'ThinkingThing',
contextBroker: {
host: '127.0.0.1',
port: '1026'
},
server: {
port: 4041
},
deviceRegistry: {
type: 'memory'
},
types: {
'ThinkingThing': {
service: 'smartGondor',
subservice: '/gardens',
type: 'ThinkingThing',
commands: [],
lazy: [],
active: [
{
name: 'humidity',
type: 'Number'
}
]
}
},
service: 'smartGondor',
subservice: '/gardens',
providerUrl: 'http://127.0.0.1:4041',
deviceRegistrationDuration: 'P1M'
};
module.exports = config;
| var config = {};
config.thinkingThings = {
logLevel: 'ERROR',
port: 8000,
root: '/thinkingthings',
sleepTime: 300
};
config.ngsi = {
logLevel: 'ERROR',
defaultType: 'ThinkingThing',
contextBroker: {
host: '192.168.56.101',
port: '1026'
},
server: {
port: 4041
},
deviceRegistry: {
type: 'memory'
},
types: {
'ThinkingThing': {
service: 'smartGondor',
subservice: '/gardens',
type: 'ThinkingThing',
commands: [],
lazy: [],
active: [
{
name: 'humidity',
type: 'Number'
}
]
}
},
service: 'smartGondor',
subservice: '/gardens',
providerUrl: 'http://192.168.56.1:4041',
deviceRegistrationDuration: 'P1M'
};
module.exports = config;
|
Move abstract declaration in front to precede visibility | <?php
/**
* This file is part of HookMeUp.
*
* (c) Sebastian Feldmann <sf@sebastian.feldmann.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace HookMeUp\Hook\Message\Validator\Rule;
use HookMeUp\Git\CommitMessage;
use HookMeUp\Hook\Message\Validator\Rule;
/**
* Class Base
*
* @package HookMeUp
* @author Sebastian Feldmann <sf@sebastian-feldmann.info>
* @link https://github.com/sebastianfeldmann/hookmeup
* @since Class available since Release 0.9.0
*/
abstract class Base implements Rule
{
/**
* Rule hint.
*
* @var string
*/
protected $hint;
/**
* @return string
*/
public function getHint()
{
return $this->hint;
}
/**
* @param \HookMeUp\Git\CommitMessage $msg
* @return bool
*/
abstract public function pass(CommitMessage $msg);
}
| <?php
/**
* This file is part of HookMeUp.
*
* (c) Sebastian Feldmann <sf@sebastian.feldmann.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace HookMeUp\Hook\Message\Validator\Rule;
use HookMeUp\Git\CommitMessage;
use HookMeUp\Hook\Message\Validator\Rule;
/**
* Class Base
*
* @package HookMeUp
* @author Sebastian Feldmann <sf@sebastian-feldmann.info>
* @link https://github.com/sebastianfeldmann/hookmeup
* @since Class available since Release 0.9.0
*/
abstract class Base implements Rule
{
/**
* Rule hint.
*
* @var string
*/
protected $hint;
/**
* @return string
*/
public function getHint()
{
return $this->hint;
}
/**
* @param \HookMeUp\Git\CommitMessage $msg
* @return bool
*/
public abstract function pass(CommitMessage $msg);
}
|
Add disk connection functions to disk | package sacloud
// propDiskConnection ディスク接続情報内包型
type propDiskConnection struct {
Connection EDiskConnection `json:",omitempty"` // ディスク接続方法
ConnectionOrder int `json:",omitempty"` // コネクション順序
}
// GetDiskConnection ディスク接続方法 取得
func (p *propDiskConnection) GetDiskConnection() EDiskConnection {
return p.Connection
}
// SetDiskConnection ディスク接続方法 設定
func (p *propDiskConnection) SetDiskConnection(conn EDiskConnection) {
p.Connection = conn
}
// GetDiskConnectionByStr ディスク接続方法 取得
func (p *propDiskConnection) GetDiskConnectionByStr() string {
return string(p.Connection)
}
// SetDiskConnectionByStr ディスク接続方法 設定
func (p *propDiskConnection) SetDiskConnectionByStr(conn string) {
p.Connection = EDiskConnection(conn)
}
// GetDiskConnectionOrder コネクション順序 取得
func (p *propDiskConnection) GetDiskConnectionOrder() int {
return p.ConnectionOrder
}
| package sacloud
// propDiskConnection ディスク接続情報内包型
type propDiskConnection struct {
Connection EDiskConnection `json:",omitempty"` // ディスク接続方法
ConnectionOrder int `json:",omitempty"` // コネクション順序
}
// GetDiskConnection ディスク接続方法 取得
func (p *propDiskConnection) GetDiskConnection() EDiskConnection {
return p.Connection
}
// SetDiskConnection ディスク接続方法 設定
func (p *propDiskConnection) SetDiskConnection(conn EDiskConnection) {
p.Connection = conn
}
// GetDiskConnectionOrder コネクション順序 取得
func (p *propDiskConnection) GetDiskConnectionOrder() int {
return p.ConnectionOrder
}
|
Move guard clause into if condition | myApp.service('breadCrumbService', function($location) {
this.crumbs = [
];
this.current = {
path: './',
display:'Inventories'
};
this.update = function(crumb) {
console.log("Updating crumbs:", crumb);
var index = this.crumbs.findIndex(function(c) {
return c.path === crumb.path;
});
if(index == -1 && crumb.path && this.current.path !== crumb.path && crumb.path !== '/') {
this.crumbs.push(this.current);
this.current = crumb;
}
else {
this.current = this.crumbs[index];
this.crumbs = this.crumbs.slice(0, index);
}
};
this.get = function(i) {
var index = i || 0;
return this.crumbs[index];
};
});
| myApp.service('breadCrumbService', function($location) {
this.crumbs = [
];
this.current = {
path: './',
display:'Inventories'
};
this.update = function(crumb) {
console.log("Updating crumbs:", crumb);
if(this.current.path === crumb.path || crumb.path === '/' || !crumb.path)
return;
var index = this.crumbs.findIndex(function(c) {
return c.path === crumb.path;
});
if(index == -1) {
this.crumbs.push(this.current);
this.current = crumb;
}
else {
this.current = this.crumbs[index];
this.crumbs = this.crumbs.slice(0, index);
}
};
this.get = function(i) {
var index = i || 0;
return this.crumbs[index];
};
});
|
Change timestamp of failed attempts to UTC | <?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\behaviors\TimestampBehavior;
class FailedAttempt extends ActiveRecord {
public static function tableName() {
return '{{%failed_attempt}}';
}
public function rules() {
return [
[['ip_address'], 'required'],
];
}
public function behaviors() {
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'time',
'updatedAtAttribute' => 'time',
'value' => new Expression('UTC_TIMESTAMP()'),
],
];
}
}
| <?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\behaviors\TimestampBehavior;
class FailedAttempt extends ActiveRecord {
public static function tableName() {
return '{{%failed_attempt}}';
}
public function rules() {
return [
[['ip_address'], 'required'],
];
}
public function behaviors() {
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'time',
'updatedAtAttribute' => 'time',
'value' => new Expression('NOW()'),
],
];
}
}
|
Add `"shapely"` dependency to extra requirements
Also, `"nbformat"` is a dependency of `"jupyter"` so we don't need to
specify both. | import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="feedinlib",
version="0.1.0dev",
description="Creating time series from pv or wind power plants.",
url="http://github.com/oemof/feedinlib",
author="oemof developer group",
author_email="windpowerlib@rl-institut.de",
license="MIT",
packages=["feedinlib"],
long_description=read("README.rst"),
long_description_content_type="text/x-rst",
zip_safe=False,
install_requires=[
"cdsapi >= 0.1.4",
"numpy >= 1.7.0",
"oedialect",
"open_FRED-cli",
"pandas >= 0.13.1",
"pvlib >= 0.6.0",
"windpowerlib >= 0.2.0",
"xarray >= 0.12.0",
],
extras_require={
"dev": ["jupyter", "pytest", "shapely", "sphinx_rtd_theme"],
"examples": ["jupyter", "shapely"],
},
)
| import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="feedinlib",
version="0.1.0dev",
description="Creating time series from pv or wind power plants.",
url="http://github.com/oemof/feedinlib",
author="oemof developer group",
author_email="windpowerlib@rl-institut.de",
license="MIT",
packages=["feedinlib"],
long_description=read("README.rst"),
long_description_content_type="text/x-rst",
zip_safe=False,
install_requires=[
"cdsapi >= 0.1.4",
"numpy >= 1.7.0",
"oedialect",
"open_FRED-cli",
"pandas >= 0.13.1",
"pvlib >= 0.6.0",
"windpowerlib >= 0.2.0",
"xarray >= 0.12.0",
],
extras_require={
"dev": ["pytest", "jupyter", "sphinx_rtd_theme", "nbformat"],
"examples": ["jupyter"],
},
)
|
Add plec json to package data | #!/usr/bin/env python
from setuptools import setup, find_packages
from oddt import __version__ as VERSION
setup(name='oddt',
version=VERSION,
description='Open Drug Discovery Toolkit',
author='Maciej Wojcikowski',
author_email='mwojcikowski@ibb.waw.pl',
url='https://github.com/oddt/oddt',
license='BSD',
packages=find_packages(),
package_data={'oddt.scoring.functions': ['NNScore/*.csv',
'RFScore/*.csv',
'PLECscore/*.json',
]},
setup_requires=['numpy'],
install_requires=open('requirements.txt', 'r').readlines(),
download_url='https://github.com/oddt/oddt/tarball/%s' % VERSION,
keywords=['cheminformatics', 'qsar', 'virtual screening', 'docking', 'pipeline'],
scripts=['bin/oddt_cli'],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
from oddt import __version__ as VERSION
setup(name='oddt',
version=VERSION,
description='Open Drug Discovery Toolkit',
author='Maciej Wojcikowski',
author_email='mwojcikowski@ibb.waw.pl',
url='https://github.com/oddt/oddt',
license='BSD',
packages=find_packages(),
package_data={'oddt.scoring.functions': ['NNScore/*.csv', 'RFScore/*.csv']},
setup_requires=['numpy'],
install_requires=open('requirements.txt', 'r').readlines(),
download_url='https://github.com/oddt/oddt/tarball/%s' % VERSION,
keywords=['cheminformatics', 'qsar', 'virtual screening', 'docking', 'pipeline'],
scripts=['bin/oddt_cli'],
)
|
Set ReturnValue for DBSubnetGroup after docs were updated
Fixes #33 | package rds
import (
"github.com/jagregory/cfval/constraints"
"github.com/jagregory/cfval/resources/common"
. "github.com/jagregory/cfval/schema"
)
// see: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbsubnet-group.html
var DBSubnetGroup = Resource{
AwsType: "AWS::RDS::DBSubnetGroup",
// Name
ReturnValue: Schema{
Type: ValueString,
},
Properties: map[string]Schema{
"DBSubnetGroupDescription": Schema{
Type: ValueString,
Required: constraints.Always,
},
"SubnetIds": Schema{
Type: Multiple(SubnetID),
Required: constraints.Always,
},
"Tags": Schema{
Type: Multiple(common.ResourceTag),
},
},
}
| package rds
import (
"github.com/jagregory/cfval/constraints"
"github.com/jagregory/cfval/resources/common"
. "github.com/jagregory/cfval/schema"
)
// see: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbsubnet-group.html
var DBSubnetGroup = Resource{
AwsType: "AWS::RDS::DBSubnetGroup",
Properties: map[string]Schema{
"DBSubnetGroupDescription": Schema{
Type: ValueString,
Required: constraints.Always,
},
"SubnetIds": Schema{
Type: Multiple(SubnetID),
Required: constraints.Always,
},
"Tags": Schema{
Type: Multiple(common.ResourceTag),
},
},
}
|
Tidy up test imports a bit | import mock
import pytest
from flask_wtf import Form
from wtforms.fields.core import Field
from wtforms.validators import StopValidation
from app.main.forms import AdminEmailAddressValidator
@mock.patch('app.main.forms.data_api_client')
class TestAdminEmailAddressValidator(object):
def setup_method(self):
self.form_mock = mock.MagicMock(Form)
self.field_mock = mock.MagicMock(Field, data='the_email_address')
self.validator = AdminEmailAddressValidator(message='The message passed to validator')
def test_admin_email_address_validator_calls_api(self, data_api_client):
self.validator(self.form_mock, self.field_mock)
data_api_client.email_is_valid_for_admin_user.assert_called_once_with('the_email_address')
def test_admin_email_address_validator_raises_with_invalid_response(self, data_api_client):
data_api_client.email_is_valid_for_admin_user.return_value = False
with pytest.raises(StopValidation, match='The message passed to validator'):
self.validator(self.form_mock, self.field_mock)
def test_admin_email_address_validator_passes_with_valid_response(self, data_api_client):
data_api_client.email_is_valid_for_admin_user.return_value = True
assert self.validator(self.form_mock, self.field_mock) is None
| import mock
import pytest
from flask.ext.wtf import Form
from wtforms.fields.core import Field
from wtforms.validators import StopValidation
from app.main.forms import AdminEmailAddressValidator
@mock.patch('app.main.forms.data_api_client')
class TestAdminEmailAddressValidator(object):
def setup_method(self):
self.form_mock = mock.MagicMock(Form)
self.field_mock = mock.MagicMock(Field, data='the_email_address')
self.validator = AdminEmailAddressValidator(message='The message passed to validator')
def test_admin_email_address_validator_calls_api(self, data_api_client):
self.validator(self.form_mock, self.field_mock)
data_api_client.email_is_valid_for_admin_user.assert_called_once_with('the_email_address')
def test_admin_email_address_validator_raises_with_invalid_response(self, data_api_client):
data_api_client.email_is_valid_for_admin_user.return_value = False
with pytest.raises(StopValidation, match='The message passed to validator'):
self.validator(self.form_mock, self.field_mock)
def test_admin_email_address_validator_passes_with_valid_response(self, data_api_client):
data_api_client.email_is_valid_for_admin_user.return_value = True
assert self.validator(self.form_mock, self.field_mock) is None
|
Convert tabs to 4 spaces | /**
* Imports svg into items with groups
* Stetson Alpha - Paper.js
*
*/
var ImportSVG = function()
{
//initialize
function initialize()
{
};
/**
*
* Takes the svg dom obj and parses the data
* to create a layer with groups (if needed) with
* items inside. Should support nested groups.
*
* takes in a svg object (xml dom)
* returns Paper.js Layer
*/
this.importSVG = function(svg)
{
return layer;
};
/**
* Creates a Paper.js Group by parsing
* a specific svg g node
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
function importGroup(svg)
{
return group;
};
/**
* Creates a Paper.js Path by parsing
* a specific svg node (rect, path, circle, polygon, etc)
* and creating the right path object based on the svg type.
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
function importPath(svg)
{
return path;
};
initialize(); // calls the init function after class is loaded
}; | /**
* Imports svg into items with groups
* Stetson Alpha - Paper.js
*
*/
var ImportSVG = function()
{
//initialize
function initialize()
{
};
/**
*
* Takes the svg dom obj and parses the data
* to create a layer with groups (if needed) with
* items inside. Should support nested groups.
*
* takes in a svg object (xml dom)
* returns Paper.js Layer
*/
this.importSVG = function(svg)
{
return layer;
};
/**
* Creates a Paper.js Group by parsing
* a specific svg g node
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
function importGroup(svg)
{
return group;
};
/**
* Creates a Paper.js Path by parsing
* a specific svg node (rect, path, circle, polygon, etc)
* and creating the right path object based on the svg type.
*
* takes in a svg object (xml dom)
* returns Paper.js Group
*/
function importPath(svg)
{
return path;
};
initialize(); // calls the init function after class is loaded
}; |
Add showNewScanForm to it tests | <?php
/*
Copyright (C) 2016 Teclib'
This file is part of Armadito Plugin for GLPI.
Armadito Plugin for GLPI 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.
Armadito Plugin for GLPI 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 Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.
**/
class AgentFormTest extends CommonTestCase
{
/**
* @test
*/
public function showForms()
{
ob_start();
$agent = new PluginArmaditoAgent();
$agent->showForm(2);
$agent->showForm(3);
PluginArmaditoAgent::showNewScanForm();
ob_end_clean();
}
}
| <?php
/*
Copyright (C) 2016 Teclib'
This file is part of Armadito Plugin for GLPI.
Armadito Plugin for GLPI 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.
Armadito Plugin for GLPI 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 Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.
**/
class AgentFormTest extends CommonTestCase
{
/**
* @test
*/
public function showForms()
{
ob_start();
$agent = new PluginArmaditoAgent();
$agent->showForm(2);
$agent->showForm(3);
ob_end_clean();
}
}
|
Fix function arguments when unknown function | var quote = require("./tools/quote"),
functions;
module.exports = function transpile(val) {
if(typeof(val) === "string") {
return "env[" + quote(val) + "]";
}
if(typeof(val) !== "object") {
return JSON.stringify(val);
}
if(!Array.isArray(val)) {
return val;
}
if(val[0] in functions) {
if(typeof(functions[val[0]]) !== "function") {
console.log(val[0]);
}
return functions[val[0]].apply(functions, val.slice(1));
}
val = val.map(transpile);
return val[0] + "(" + val.slice(1).join(", ") + ")";
};
functions = require("./functions");
| var quote = require("./tools/quote"),
functions;
module.exports = function transpile(val) {
if(typeof(val) === "string") {
return "env[" + quote(val) + "]";
}
if(typeof(val) !== "object") {
return JSON.stringify(val);
}
if(!Array.isArray(val)) {
return val;
}
if(val[0] in functions) {
if(typeof(functions[val[0]]) !== "function") {
console.log(val[0]);
}
return functions[val[0]].apply(functions, val.slice(1));
}
return transpile(val[0]) + "(" + val.slice(1).join(", ") + ")";
};
functions = require("./functions");
|
Allow overriding of vee-validate built-in validation messages | import Vue from 'vue'
import VueI18n from 'vue-i18n'
import deepmerge from 'deepmerge'
import availableLocales from './availableLocales'
import en from '@/locales/en.json'
import de from '@/locales/de.json'
import deCHScout from '@/locales/de-CH-scout.json'
import validationEn from 'vee-validate/dist/locale/en.json'
import validationDe from 'vee-validate/dist/locale/de.json'
Vue.use(VueI18n)
export default new VueI18n({
locale: 'de',
fallbackLocale: 'en',
messages: deepmerge({
de: {
validation: validationDe.messages
},
en: {
validation: validationEn.messages
}
}, { en, de, 'de-CH-scout': deCHScout }),
silentTranslationWarn: true,
availableLocales
})
| import Vue from 'vue'
import VueI18n from 'vue-i18n'
import deepmerge from 'deepmerge'
import availableLocales from './availableLocales'
import en from '@/locales/en.json'
import de from '@/locales/de.json'
import deCHScout from '@/locales/de-CH-scout.json'
import validationEn from 'vee-validate/dist/locale/en.json'
import validationDe from 'vee-validate/dist/locale/de.json'
Vue.use(VueI18n)
export default new VueI18n({
locale: 'de',
fallbackLocale: 'en',
messages: deepmerge({ en, de, 'de-CH-scout': deCHScout }, {
de: {
validation: validationDe.messages
},
en: {
validation: validationEn.messages
}
}),
silentTranslationWarn: true,
availableLocales
})
|
Remove period after package description | """setup.py"""
#pylint:disable=line-too-long
from setuptools import setup
from codecs import open as codecs_open
with codecs_open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with codecs_open('HISTORY.rst', 'r', 'utf-8') as f:
history = f.read()
setup(
name='jsonrpcclient',
version='2.0.1',
description='JSON-RPC client library',
long_description=readme + '\n\n' + history,
author='Beau Barker',
author_email='beauinmelbourne@gmail.com',
url='https://jsonrpcclient.readthedocs.org/',
packages=['jsonrpcclient'],
package_data={'jsonrpcclient': ['response-schema.json']},
include_package_data=True,
install_requires=['jsonschema', 'future'],
tests_require=['tox'],
classifiers=[
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
| """setup.py"""
#pylint:disable=line-too-long
from setuptools import setup
from codecs import open as codecs_open
with codecs_open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
with codecs_open('HISTORY.rst', 'r', 'utf-8') as f:
history = f.read()
setup(
name='jsonrpcclient',
version='2.0.1',
description='JSON-RPC client library.',
long_description=readme + '\n\n' + history,
author='Beau Barker',
author_email='beauinmelbourne@gmail.com',
url='https://jsonrpcclient.readthedocs.org/',
packages=['jsonrpcclient'],
package_data={'jsonrpcclient': ['response-schema.json']},
include_package_data=True,
install_requires=['jsonschema', 'future'],
tests_require=['tox'],
classifiers=[
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
)
|
Fix missing views when initial route hash on URL | /**
* Main entry point to simpleshelf app.
*/
var $ = require("jquery"),
Backbone = require("backbone"),
_ = require("underscore"),
appsetup = require("./appsetup.js"),
appevents = require("./appevents.js"),
simpleshelfApp = require("./app.js").app,
Router = require("./router.js");
// To support Bootstrap, add jQuery & Tether to the global namespace.
window.$ = window.jQuery = require('jquery');
window.Tether = require('tether');
$(document).ready(function() {
// Load plugins and widgets on the global $.
// require(["widgets/tags"]);
// Override BB sync.
appsetup.overrideBackboneSync(Backbone, _);
this.app = simpleshelfApp; // singleton
// Setup top-level app objects.
this.app.router = new Router({
views: this.app.views,
catalog: this.app.catalog
});
appevents.setupAppEvents(this.app);
appevents.hookupAppEvents(this.app);
// Start Backbone routing.
// NOTE: when silent===true, no views are automatically invoked.
// So if the hash is on an existing route (like ``#login``), nothing will appear to happen.
var historyStart = Backbone.history.start();
console.info("[main]", "Backbone.history.start",
historyStart, (historyStart ? "Found initial matching route" : "No initial matching route")
);
// Start app.
this.app.run();
});
| /**
* Main entry point to simpleshelf app.
*/
var $ = require("jquery"),
Backbone = require("backbone"),
_ = require("underscore"),
appsetup = require("./appsetup.js"),
appevents = require("./appevents.js"),
simpleshelfApp = require("./app.js").app,
Router = require("./router.js");
// To support Bootstrap, add jQuery & Tether to the global namespace.
window.$ = window.jQuery = require('jquery');
window.Tether = require('tether');
$(document).ready(function() {
// Load plugins and widgets on the global $.
// require(["widgets/tags"]);
// Override BB sync.
appsetup.overrideBackboneSync(Backbone, _);
this.app = simpleshelfApp; // singleton
// Setup top-level app objects.
this.app.router = new Router({
views: this.app.views,
catalog: this.app.catalog
});
appevents.setupAppEvents(this.app);
appevents.hookupAppEvents(this.app);
// Start Backbone routing.
// NOTE: when silent===true, no views are automatically invoked.
// So if the hash is on an existing route (like ``#login``), nothing will appear to happen.
// TODO: make the .history.start() and the app.run() call work better together.
Backbone.history.start({silent: true});
// Start app.
this.app.run();
});
|
Add tdd to increase coverage | from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.test import TestCase
from model_utils.fields import UUIDField
class UUIDFieldTests(TestCase):
def test_uuid_version_default(self):
instance = UUIDField()
self.assertEqual(instance.default, uuid.uuid4)
def test_uuid_version_1(self):
instance = UUIDField(version=1)
self.assertEqual(instance.default, uuid.uuid1)
def test_uuid_version_2_error(self):
self.assertRaises(ValidationError, UUIDField, 'version', 2)
def test_uuid_version_3(self):
instance = UUIDField(version=3)
self.assertEqual(instance.default, uuid.uuid3)
def test_uuid_version_4(self):
instance = UUIDField(version=4)
self.assertEqual(instance.default, uuid.uuid4)
def test_uuid_version_5(self):
instance = UUIDField(version=5)
self.assertEqual(instance.default, uuid.uuid5)
def test_uuid_version_bellow_min(self):
self.assertRaises(ValidationError, UUIDField, 'version', 0)
def test_uuid_version_above_max(self):
self.assertRaises(ValidationError, UUIDField, 'version', 6)
| from __future__ import unicode_literals
import uuid
from django.core.exceptions import ValidationError
from django.test import TestCase
from model_utils.fields import UUIDField
class UUIDFieldTests(TestCase):
def test_uuid_version_default(self):
instance = UUIDField()
self.assertEqual(instance.default, uuid.uuid4)
def test_uuid_version_1(self):
instance = UUIDField(version=1)
self.assertEqual(instance.default, uuid.uuid1)
def test_uuid_version_2_error(self):
self.assertRaises(ValidationError, UUIDField, 'version', 2)
def test_uuid_version_3(self):
instance = UUIDField(version=3)
self.assertEqual(instance.default, uuid.uuid3)
def test_uuid_version_4(self):
instance = UUIDField(version=4)
self.assertEqual(instance.default, uuid.uuid4)
def test_uuid_version_5(self):
instance = UUIDField(version=5)
self.assertEqual(instance.default, uuid.uuid5)
|
Remove unused eslint env options | 'use strict'
const { env, platform } = process
module.exports = {
extends: [
'eslint:recommended',
'eslint-config-airbnb-base',
'plugin:prettier/recommended',
],
env: {
jest: true,
},
parserOptions: {
sourceType: 'script',
},
rules: {
// TODO FIXME workaround for git + prettier line ending issue on Travis for Windows OS:
...(env.TRAVIS &&
platform === 'win32' && {
'prettier/prettier': ['error', { endOfLine: 'auto' }],
}),
// TODO FIXME turn off temporary, to make eslint pass
'class-methods-use-this': 'off',
'consistent-return': 'off',
'no-console': 'off',
'no-multi-assign': 'off',
'no-param-reassign': 'off',
'no-restricted-syntax': 'off',
'no-shadow': 'off',
'no-underscore-dangle': 'off',
'no-use-before-define': 'off',
},
}
| 'use strict'
const { env, platform } = process
module.exports = {
extends: [
'eslint:recommended',
'eslint-config-airbnb-base',
'plugin:prettier/recommended',
],
env: {
es6: true,
jest: true,
node: true,
},
parserOptions: {
sourceType: 'script',
},
rules: {
// TODO FIXME workaround for git + prettier line ending issue on Travis for Windows OS:
...(env.TRAVIS &&
platform === 'win32' && {
'prettier/prettier': ['error', { endOfLine: 'auto' }],
}),
// TODO FIXME turn off temporary, to make eslint pass
'class-methods-use-this': 'off',
'consistent-return': 'off',
'no-console': 'off',
'no-multi-assign': 'off',
'no-param-reassign': 'off',
'no-restricted-syntax': 'off',
'no-shadow': 'off',
'no-underscore-dangle': 'off',
'no-use-before-define': 'off',
},
}
|
Remove destination parameter and watch correct path | var browserify = require('browserify');
var watchify = require('watchify');
var koars = require('koars-utils')({module: 'assets', asset:'js'});
var path = require('path');
module.exports = function(src, excludes) {
//Setup our cache, timestamp and watchify instance
var cache, time = new Date();
var w = watchify(browserify(path.join(process.cwd(), src), watchify.args));
//Exclude all specified modules
if(excludes) excludes.forEach(w.exclude.bind(w));
//Run the initial bundle and listen for updates
cache = bundle();
if(koars.dev()) w.on('update', function() {
cache = bundle();
});
//Exclude handlebars, if needed, so we use the handlebars instance which has our helpers attached
//Then bundle the files, update the timestamp and log our success/failure
function bundle() {
return new Promise(function(resolve, reject) {
w.bundle(function(err, bundle) {
if(!err) {
time = new Date();
koars.log.debug('Rebuilt js bundle');
resolve(bundle);
} else {
koars.log.warn(err, 'Failed to build js bundle');
reject(err);
}
});
});
}
//Return a middleware generator function to serve our cached bundle upon request
return function *(next) {
this.body = yield cache;
this.lastModified = time;
this.type = 'text/javascript';
};
};
| var browserify = require('browserify');
var watchify = require('watchify');
var koars = require('koars-utils')({module: 'assets', asset:'js'});
module.exports = function(src, dest, excludes) {
//Setup our cache, timestamp and watchify instance
var cache, time = new Date();
var w = watchify(browserify(src, watchify.args));
//Exclude all specified modules
if(excludes) excludes.forEach(w.exclude.bind(w));
//Run the initial bundle and listen for updates
cache = bundle();
if(koars.dev()) w.on('update', function() {
cache = bundle();
});
//Exclude handlebars, if needed, so we use the handlebars instance which has our helpers attached
//Then bundle the files, update the timestamp and log our success/failure
function bundle() {
return new Promise(function(resolve, reject) {
w.bundle(function(err, bundle) {
if(!err) {
time = new Date();
koars.log.debug('Rebuilt js bundle');
resolve(bundle);
} else {
koars.log.warn(err, 'Failed to build js bundle');
reject(err);
}
});
});
}
//Return a middleware generator function to serve our cached bundle upon request
return function *(next) {
this.body = yield cache;
this.lastModified = time;
this.type = 'text/javascript';
};
}; |
[test-studio] Add project-users widget to test-studio dashboard config | export default {
widgets: [
{name: 'sanity-tutorials', layout: {width: 'full'}},
{name: 'document-list'},
{name: 'document-count'},
{name: 'project-users'},
{
name: 'project-info',
layout: {
width: 'medium'
},
options: {
data: [
{title: 'Frontend', value: 'https://asdf.heroku.com/greedy-goblin', category: 'apps'},
{title: 'Strange endpoint', value: 'https://example.com/v1/strange', category: 'apis'},
{title: 'With strawberry jam?', value: 'Yes', category: 'Waffles'}
]
}
},
// {name: 'cats', options: {imageWidth: 90}},
{name: 'stack-overview', layout: {width: 'full'}}
]
}
| export default {
widgets: [
{name: 'sanity-tutorials', layout: {width: 'full'}},
{name: 'document-list'},
{name: 'document-count'},
// {name: 'cats', layout: {width: 'medium'}, options: {imageWidth: 50}},
// {name: 'cats', layout: {width: 'medium'}, options: {imageWidth: 150}},
{
name: 'project-info',
layout: {
width: 'medium'
},
options: {
data: [
{title: 'Frontend', value: 'https://asdf.heroku.com/greedy-goblin', category: 'apps'},
{title: 'Strange endpoint', value: 'https://example.com/v1/strange', category: 'apis'},
{title: 'With strawberry jam?', value: 'Yes', category: 'Waffles'}
]
}
},
// {name: 'cats', options: {imageWidth: 90}},
{name: 'stack-overview', layout: {width: 'full'}}
]
}
|
Determine winning hand & compare to nut hand. | from itertools import combinations
from deuces.deuces import Card, Evaluator, Deck
from nuts import nut_hand
evaluator = Evaluator()
deck = Deck()
flop = deck.draw(3)
def omaha_eval(hole, board):
assert(len(hole)) == 4
ranks = []
for ph in combinations(hole, 2):
thisrank = evaluator.evaluate(list(ph), board)
ranks.append(thisrank)
return min(ranks)
def r2t(x):
return evaluator.class_to_string(evaluator.get_rank_class(x))
def r2c(x):
return evaluator.get_rank_class(x)
def list_to_pretty_str(card_ints):
output = " "
for i in range(len(card_ints)):
c = card_ints[i]
if i != len(card_ints) - 1:
output += Card.int_to_pretty_str(c) + ","
else:
output += Card.int_to_pretty_str(c) + " "
return output
print list_to_pretty_str(flop)
rank_clasess= []
for i in range(6):
player = deck.draw(4)
realrank = omaha_eval(player, flop)
print list_to_pretty_str(player), r2t(realrank)
rank_clasess.append(r2c(realrank))
print
print "nuts = ", nut_hand(flop), ". win = ", evaluator.class_to_string(min(rank_clasess))
| from itertools import combinations
from deuces.deuces import Card, Evaluator, Deck
from nuts import nut_hand
evaluator = Evaluator()
deck = Deck()
flop = deck.draw(3)
def omaha_eval(hole, board):
assert(len(hole)) == 4
ranks = []
for ph in combinations(hole, 2):
thisrank = evaluator.evaluate(list(ph), board)
ranks.append(thisrank)
return min(ranks)
def r2t(x):
return evaluator.class_to_string(evaluator.get_rank_class(x))
def list_to_pretty_str(card_ints):
output = " "
for i in range(len(card_ints)):
c = card_ints[i]
if i != len(card_ints) - 1:
output += Card.int_to_pretty_str(c) + ","
else:
output += Card.int_to_pretty_str(c) + " "
return output
print list_to_pretty_str(flop), "nuts = ", nut_hand(flop)
for i in range(6):
player = deck.draw(4)
realrank = omaha_eval(player, flop)
realtext = r2t(realrank)
print list_to_pretty_str(player), realtext
|
Add 2 tests for Utils | import os
from unittest import TestCase
import requests
from furikura import utils
from furikura.config import Config
config_cls = Config()
def test_request():
requests.get('https://example.com')
class TestUtils(TestCase):
def test_get_file(self):
self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile")
def test_check_connection(self):
self.addTypeEqualityFunc(type, utils.check_connection(test_request))
def test_autostart(self):
os.makedirs(os.path.expanduser('~/.config/autostart/'), exist_ok=True)
utils.autostart('add')
self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
utils.autostart('remove')
self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
def test_check_lock(self):
os.makedirs(os.path.expanduser('~/.config/furikura/'), exist_ok=True)
utils.check_lock()
self.assertTrue(os.path.isfile(config_cls.LOCKFILE))
def test_debug(self):
self.addTypeEqualityFunc(type, utils.debug(test_request))
| import os
from unittest import TestCase
import requests
from furikura import utils
def test_request():
requests.get('https://example.com')
class TestUtils(TestCase):
def test_get_file(self):
self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile")
def test_check_connection(self):
self.addTypeEqualityFunc(type, utils.check_connection(test_request))
def test_autostart(self):
os.makedirs(os.path.expanduser('~/.config/autostart/'), exist_ok=True)
utils.autostart('add')
self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
utils.autostart('remove')
self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
|
Allow adding custom response listeners | var http = require("http");
function HttpServer(config) {
this.port = config.port || 8181;
this.address = config.address || "localhost";
this.options = {
data: null,
resCode: 200
};
}
HttpServer.prototype.start = function (fn) {
this.server = http.createServer(function (req, res) {
res.writeHead(this.options.resCode, {"Content-Type": "application/json"});
res.end(JSON.stringify(this.options.data));
}.bind(this)).listen(this.port, this.address, fn);
return this;
};
HttpServer.prototype.setup = function (data, resCode) {
this.options.data = data;
this.options.resCode = resCode || 200;
return this;
};
HttpServer.prototype.on = function (event, fn) {
this.server.on(event, fn);
};
HttpServer.prototype.stop = function (fn) {
this.server.close();
if (fn) {
fn();
}
};
exports.HttpServer = HttpServer;
| var http = require("http");
function HttpServer(config) {
this.port = config.port || 8181;
this.address = config.address || "localhost";
this.options = {
data: null,
resCode: 200
};
}
HttpServer.prototype.start = function (fn) {
this.server = http.createServer(function (req, res) {
res.writeHead(this.options.resCode, {"Content-Type": "application/json"});
res.end(JSON.stringify(this.options.data));
}.bind(this)).listen(this.port, this.address, fn);
return this;
};
HttpServer.prototype.setup = function (data, resCode) {
this.options.data = data;
this.options.resCode = resCode || 200;
return this;
};
HttpServer.prototype.stop = function (fn) {
this.server.close();
if (fn) {
fn();
}
};
exports.HttpServer = HttpServer;
|
Fix argument passthrough to resolver | 'use strict';
import clone from 'clone';
import extend from 'xtend/mutable';
const methods = [
'card.createToken',
'bankAccount.createToken',
'bitcoinReceiver.createReceiver',
'bitcoinReceiver.pollReceiver'
];
export default function (Stripe, Promise) {
if (!Promise) throw new Error('Promise constructor must be provided');
return methods.reduce((Stripe, method) => {
const [context, name] = method.split('.');
const fn = Stripe[context][name];
Stripe[context][name] = promisify(Promise, fn, context, stripeResponseHandler);
return Stripe;
}, clone(Stripe));
}
function promisify (Promise, fn, context, resolver) {
return function promisified (...args) {
return new Promise((resolve, reject) => {
fn.apply(context, args.concat(function () {
resolver.apply({resolve, reject}, arguments);
}));
});
};
}
function stripeResponseHandler (status, response) {
if (response.error) {
this.reject(extend(new Error(), response.error));
}
else {
this.resolve(response);
}
}
| 'use strict';
import clone from 'clone';
import extend from 'xtend/mutable';
const methods = [
'card.createToken',
'bankAccount.createToken',
'bitcoinReceiver.createReceiver',
'bitcoinReceiver.pollReceiver'
];
export default function (Stripe, Promise) {
if (!Promise) throw new Error('Promise constructor must be provided');
return methods.reduce((Stripe, method) => {
const [context, name] = method.split('.');
const fn = Stripe[context][name];
Stripe[context][name] = promisify(Promise, fn, context, stripeResponseHandler);
return Stripe;
}, clone(Stripe));
}
function promisify (Promise, fn, context, resolver) {
return function promisified (...args) {
return new Promise((resolve, reject) => {
fn.apply(context, args.concat(() => {
resolver.apply({resolve, reject}, arguments);
}));
});
};
}
function stripeResponseHandler (status, response) {
if (response.error) {
this.reject(extend(new Error(), response.error));
}
else {
this.resolve(response);
}
}
|
Reduce cache time to reduce cors problems | 'use strict';
const tickerGenerator = require('./functions/ticker');
const fetch = require('node-fetch');
const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
const _ = require('lodash');
const s3 = new AWS.S3();
module.exports.ticker = (event, context, callback) => {
tickerGenerator()
.then(files => {
return Promise.all(_.map(files, (contents, filename) => {
return s3.putObject({
Bucket: process.env.BUCKET,
Key: filename,
Body: contents,
ContentType: 'application/json',
ACL: 'public-read',
CacheControl: 'public, max-age=5',
}).promise()
}))
})
.then(v => callback(null, v), callback);
};
| 'use strict';
const tickerGenerator = require('./functions/ticker');
const fetch = require('node-fetch');
const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
const _ = require('lodash');
const s3 = new AWS.S3();
module.exports.ticker = (event, context, callback) => {
tickerGenerator()
.then(files => {
return Promise.all(_.map(files, (contents, filename) => {
return s3.putObject({
Bucket: process.env.BUCKET,
Key: filename,
Body: contents,
ContentType: 'application/json',
ACL: 'public-read',
CacheControl: 'public, max-age=30',
}).promise()
}))
})
.then(v => callback(null, v), callback);
};
|
Fix: Use rsponse.json() to fix test-failure on json-3.5 | from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import TemplateDoesNotExist
from django.test import TestCase
from core.models import Image
from core.tests import create_user
from users.models import User
__all__ = ['CreateImageTest']
class CreateImageTest(TestCase):
def setUp(self):
self.user = create_user("default")
self.client.login(username=self.user.username, password='password')
def tearDown(self):
User.objects.all().delete()
Image.objects.all().delete()
def test_post(self):
with open('logo.png', mode='rb') as image:
response = self.client.post(reverse('image-list'), {'image': image})
image = Image.objects.latest('pk')
self.assertEqual(response.json()['id'], image.pk)
def test_post_error(self):
response = self.client.post(reverse('image-list'), {'image': None})
self.assertEqual(
response.json(),
{
'image': [
'The submitted data was not a file. '
'Check the encoding type on the form.'
]
}
)
| from django.conf import settings
from django.core.urlresolvers import reverse
from django.template import TemplateDoesNotExist
from django.test import TestCase
from core.models import Image
from core.tests import create_user
from users.models import User
__all__ = ['CreateImageTest']
class CreateImageTest(TestCase):
def setUp(self):
self.user = create_user("default")
self.client.login(username=self.user.username, password='password')
def tearDown(self):
User.objects.all().delete()
Image.objects.all().delete()
def test_post(self):
with open('logo.png', mode='rb') as image:
response = self.client.post(reverse('image-list'), {'image': image})
image = Image.objects.latest('pk')
self.assertEqual(response.json()['id'], image.pk)
def test_post_error(self):
response = self.client.post(reverse('image-list'), {'image': None})
self.assertJSONEqual(
response.content,
{
'image': [
'The submitted data was not a file. '
'Check the encoding type on the form.'
]
}
)
|
Add splash page to sitemap | from common.helpers.constants import FrontEndSection
from django.conf import settings
from django.contrib.sitemaps import Sitemap
from .models import Project
from datetime import date
class SectionSitemap(Sitemap):
protocol = "https"
changefreq = "monthly"
priority = 0.5
# TODO: Update this date for each release
lastmod = settings.SITE_LAST_UPDATED
pages = [
str(FrontEndSection.AboutUs.value),
str(FrontEndSection.FindProjects.value),
str(FrontEndSection.FindProjects.value) + '&showSplash=1',
str(FrontEndSection.PartnerWithUs.value),
str(FrontEndSection.Donate.value),
str(FrontEndSection.Press.value),
str(FrontEndSection.ContactUs.value)
]
def items(self):
return self.pages
def location(self, page):
return '/index/?section=' + page
class ProjectSitemap(Sitemap):
protocol = "https"
changefreq = "daily"
priority = 0.5
def items(self):
return Project.objects.filter(is_searchable=True).order_by('id')
def location(self, project):
return '/index/?section=AboutProject&id=' + str(project.id)
def lastmod(self, project):
return project.project_date_modified
| from common.helpers.constants import FrontEndSection
from django.conf import settings
from django.contrib.sitemaps import Sitemap
from .models import Project
from datetime import date
class SectionSitemap(Sitemap):
protocol = "https"
changefreq = "monthly"
priority = 0.5
# TODO: Update this date for each release
lastmod = settings.SITE_LAST_UPDATED
sections = [FrontEndSection.AboutUs, FrontEndSection.FindProjects, FrontEndSection.PartnerWithUs, FrontEndSection.Donate,
FrontEndSection.Press, FrontEndSection.ContactUs]
def items(self):
return self.sections
def location(self, section):
return '/index/?section=' + str(section.value)
class ProjectSitemap(Sitemap):
protocol = "https"
changefreq = "daily"
priority = 0.5
def items(self):
return Project.objects.filter(is_searchable=True).order_by('id')
def location(self, project):
return '/index/?section=AboutProject&id=' + str(project.id)
def lastmod(self, project):
return project.project_date_modified
|
Disable test untestable without x server | package org.jrebirth.af.core.command.basic.multi;
import org.jrebirth.af.core.command.basic.BasicCommandTest;
import org.junit.Ignore;
import org.junit.Test;
@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {
@Test
public void sequentialTest1() {
System.out.println("Sequential Test default");
runCommand(DefaultSequentialCommand.class);
}
@Test
public void sequentialTest2() {
System.out.println("Sequential Test annotation");
runCommand(AnnotatedSequentialCommand.class);
}
@Test
public void sequentialTest3() {
System.out.println("Sequential Test constructor");
runCommand(ConstructorSequentialCommand.class);
}
@Test
public void parallelTest1() {
System.out.println("Parallel Test default");
runCommand(DefaultParallelCommand.class);
}
@Test
public void parallelTest2() {
System.out.println("Parallel Test annotation");
runCommand(AnnotatedParallelCommand.class);
}
@Test
public void parallelTest3() {
System.out.println("Parallel Test constructor");
runCommand(ConstructorParallelCommand.class);
}
}
| package org.jrebirth.af.core.command.basic.multi;
import org.jrebirth.af.core.command.basic.BasicCommandTest;
import org.junit.Test;
//@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {
@Test
public void sequentialTest1() {
System.out.println("Sequential Test default");
runCommand(DefaultSequentialCommand.class);
}
@Test
public void sequentialTest2() {
System.out.println("Sequential Test annotation");
runCommand(AnnotatedSequentialCommand.class);
}
@Test
public void sequentialTest3() {
System.out.println("Sequential Test constructor");
runCommand(ConstructorSequentialCommand.class);
}
@Test
public void parallelTest1() {
System.out.println("Parallel Test default");
runCommand(DefaultParallelCommand.class);
}
@Test
public void parallelTest2() {
System.out.println("Parallel Test annotation");
runCommand(AnnotatedParallelCommand.class);
}
@Test
public void parallelTest3() {
System.out.println("Parallel Test constructor");
runCommand(ConstructorParallelCommand.class);
}
}
|
Refactor the app startup to be async | module.exports = async () => {
require('@maxdome/env');
const logging = require('@maxdome/logging')({
level: process.env.LOG_LEVEL,
});
require('@maxdome/exception-handling')({ logging });
const appLogger = logging('app');
appLogger.info('initializing server');
const app = require('@maxdome/express')();
app.use(require('@maxdome/logging-middleware')({ logging }));
app.use('/docs', require('@maxdome/swagger')({ config: 'docs/swagger.yml' }));
app.get('/health', require('@maxdome/health').controller());
app.use('/info', require('@maxdome/info')());
app.use('/api', require('./api')());
app.use(require('@maxdome/logging-middleware').errorLogging({ logging }));
return { app, logging };
};
if (!module.parent) {
(async () => {
const { app, logging } = await module.exports();
const port = process.env.PORT || 3000;
app.listen(port, () => {
logging('app').info(`Server listening on ${port}`);
});
})();
}
| require('@maxdome/env');
const logging = require('@maxdome/logging')({
level: process.env.LOG_LEVEL,
});
require('@maxdome/exception-handling')({ logging });
const appLogger = logging('app');
appLogger.info('initializing server');
const app = require('@maxdome/express')();
app.use(require('@maxdome/logging-middleware')({ logging }));
app.use('/docs', require('@maxdome/swagger')({ config: 'docs/swagger.yml' }));
app.get('/health', require('@maxdome/health').controller());
app.use('/info', require('@maxdome/info')());
app.use('/api', require('./api')());
app.use(require('@maxdome/logging-middleware').errorLogging({ logging }));
if (!module.parent) {
const port = process.env.PORT || 3000;
app.listen(port, () => {
appLogger.info(`Server listening on ${port}`);
});
}
module.exports = app;
|
Update version number to 2.7.0
and bump buildbot required version to 2.8.4. | from setuptools import setup, find_packages
BUILDBOTVERSION = '2.8.4'
setup(
name='autobuilder',
version='2.7.0',
packages=find_packages(),
license='MIT',
author='Matt Madison',
author_email='matt@madison.systems',
include_package_data=True,
package_data={
'autobuilder': ['templates/*.txt']
},
install_requires=['aws-secretsmanager-caching',
'buildbot[tls]>=' + BUILDBOTVERSION,
'buildbot-www>=' + BUILDBOTVERSION,
'buildbot-console-view>=' + BUILDBOTVERSION,
'buildbot-grid-view>=' + BUILDBOTVERSION,
'buildbot-waterfall-view>=' + BUILDBOTVERSION,
'buildbot-badges>=' + BUILDBOTVERSION,
'boto3', 'botocore',
'treq', 'twisted',
'python-dateutil',
'jinja2']
)
| from setuptools import setup, find_packages
BUILDBOTVERSION = '2.8.2'
setup(
name='autobuilder',
version='2.6.95',
packages=find_packages(),
license='MIT',
author='Matt Madison',
author_email='matt@madison.systems',
include_package_data=True,
package_data={
'autobuilder': ['templates/*.txt']
},
install_requires=['aws-secretsmanager-caching',
'buildbot[tls]>=' + BUILDBOTVERSION,
'buildbot-www>=' + BUILDBOTVERSION,
'buildbot-console-view>=' + BUILDBOTVERSION,
'buildbot-grid-view>=' + BUILDBOTVERSION,
'buildbot-waterfall-view>=' + BUILDBOTVERSION,
'buildbot-badges>=' + BUILDBOTVERSION,
'boto3', 'botocore',
'treq', 'twisted',
'python-dateutil',
'jinja2']
)
|
Drop references from popped classes. | package com.thoughtworks.xstream.core.util;
public final class ClassStack {
private Class[] stack;
private int pointer;
public ClassStack(int initialCapacity) {
stack = new Class[initialCapacity];
}
public void push(Class value) {
if (pointer + 1 >= stack.length) {
resizeStack(stack.length * 2);
}
stack[pointer++] = value;
}
public void popSilently() {
stack[--pointer] = null;
}
public Class pop() {
final Class result = stack[--pointer];
stack[pointer] = null;
return result;
}
public Class peek() {
return pointer == 0 ? null : stack[pointer - 1];
}
public int size() {
return pointer;
}
public Class get(int i) {
return stack[i];
}
private void resizeStack(int newCapacity) {
Class[] newStack = new Class[newCapacity];
System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
stack = newStack;
}
}
| package com.thoughtworks.xstream.core.util;
public final class ClassStack {
private Class[] stack;
private int pointer;
public ClassStack(int initialCapacity) {
stack = new Class[initialCapacity];
}
public void push(Class value) {
if (pointer + 1 >= stack.length) {
resizeStack(stack.length * 2);
}
stack[pointer++] = value;
}
public void popSilently() {
pointer--;
}
public Class pop() {
return stack[--pointer];
}
public Class peek() {
return pointer == 0 ? null : stack[pointer - 1];
}
public int size() {
return pointer;
}
public Class get(int i) {
return stack[i];
}
private void resizeStack(int newCapacity) {
Class[] newStack = new Class[newCapacity];
System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
stack = newStack;
}
}
|
Add NDDataBase to package import | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The `astropy.nddata` subpackage provides the `~astropy.nddata.NDData`
class and related tools to manage n-dimensional array-based data (e.g.
CCD images, IFU Data, grid-based simulation data, ...). This is more than
just `numpy.ndarray` objects, because it provides metadata that cannot
be easily provided by a single array.
"""
from .nddata import *
from .nddatabase import *
from .nduncertainty import *
from .flag_collection import *
from .decorators import *
from .arithmetic import *
from .. import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.nddata`.
"""
warn_unsupported_correlated = _config.ConfigItem(
True,
'Whether to issue a warning if `~astropy.nddata.NDData` arithmetic '
'is performed with uncertainties and the uncertainties do not '
'support the propagation of correlated uncertainties.'
)
warn_setting_unit_directly = _config.ConfigItem(
True,
'Whether to issue a warning when the `~astropy.nddata.NDData` unit '
'attribute is changed from a non-``None`` value to another value '
'that data values/uncertainties are not scaled with the unit change.'
)
conf = Conf()
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The `astropy.nddata` subpackage provides the `~astropy.nddata.NDData`
class and related tools to manage n-dimensional array-based data (e.g.
CCD images, IFU Data, grid-based simulation data, ...). This is more than
just `numpy.ndarray` objects, because it provides metadata that cannot
be easily provided by a single array.
"""
from .nddata import *
from .nduncertainty import *
from .flag_collection import *
from .decorators import *
from .arithmetic import *
from .. import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.nddata`.
"""
warn_unsupported_correlated = _config.ConfigItem(
True,
'Whether to issue a warning if `~astropy.nddata.NDData` arithmetic '
'is performed with uncertainties and the uncertainties do not '
'support the propagation of correlated uncertainties.'
)
warn_setting_unit_directly = _config.ConfigItem(
True,
'Whether to issue a warning when the `~astropy.nddata.NDData` unit '
'attribute is changed from a non-``None`` value to another value '
'that data values/uncertainties are not scaled with the unit change.'
)
conf = Conf()
|
Allow to dump frontend consumers in JSON | <?php
namespace Wizbii\PipelineBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Wizbii\PipelineBundle\Service\Pipeline;
use Wizbii\PipelineBundle\Service\PipelineProvider;
class FrontendPipelineCommand extends ContainerAwareCommand
{
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$consumers = $this->getConsumers($input->getOption('direct'));
$asJson = $input->getOption('json');
$output->write($asJson ? json_encode($consumers) : join(" ", $consumers));
}
protected function configure()
{
$this
->setName('pipeline:frontend:list')
->addOption('direct', null, InputOption::VALUE_NONE)
->addOption('json', null, InputOption::VALUE_NONE)
;
}
protected function getConsumers(bool $directConsumers)
{
$serviceId = $directConsumers ? "pipeline.consumers.direct" : "pipeline.consumers";
return $this->getContainer()->get($serviceId)->getArrayCopy();
}
} | <?php
namespace Wizbii\PipelineBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Wizbii\PipelineBundle\Service\Pipeline;
use Wizbii\PipelineBundle\Service\PipelineProvider;
class FrontendPipelineCommand extends ContainerAwareCommand
{
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$consumers = $this->getConsumers($input->getOption('direct'));
echo join(" ", $consumers->getArrayCopy());
}
protected function configure()
{
$this
->setName('pipeline:frontend:list')
->addOption('direct', null, InputOption::VALUE_NONE)
;
}
protected function getConsumers(bool $directConsumers)
{
$serviceId = $directConsumers ? "pipeline.consumers.direct" : "pipeline.consumers";
return $this->getContainer()->get($serviceId);
}
} |
Add assertion for dot files | package com.github.ferstl.depgraph;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.takari.maven.testing.TestResources;
import io.takari.maven.testing.executor.MavenExecutionResult;
import io.takari.maven.testing.executor.MavenRuntime;
import io.takari.maven.testing.executor.MavenRuntime.MavenRuntimeBuilder;
import io.takari.maven.testing.executor.MavenVersions;
import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner;
import static io.takari.maven.testing.TestResources.assertFilesPresent;
@RunWith(MavenJUnitTestRunner.class)
@MavenVersions("3.3.9")
public class IntegrationTest {
@Rule
public final TestResources resources = new TestResources();
private final MavenRuntime mavenRuntime;
public IntegrationTest(MavenRuntimeBuilder builder) throws Exception {
this.mavenRuntime = builder.build();
}
@Test
public void graph() throws Exception {
File basedir = this.resources.getBasedir("depgraph-maven-plugin-test");
MavenExecutionResult result = this.mavenRuntime
.forProject(basedir)
.execute("clean", "depgraph:graph");
result.assertErrorFreeLog();
assertFilesPresent(
basedir,
"module-1/target/dependency-graph.dot",
"module-2/target/dependency-graph.dot",
"sub-parent/module-3/target/dependency-graph.dot");
}
}
| package com.github.ferstl.depgraph;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.takari.maven.testing.TestResources;
import io.takari.maven.testing.executor.MavenExecutionResult;
import io.takari.maven.testing.executor.MavenRuntime;
import io.takari.maven.testing.executor.MavenRuntime.MavenRuntimeBuilder;
import io.takari.maven.testing.executor.MavenVersions;
import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner;
@RunWith(MavenJUnitTestRunner.class)
@MavenVersions("3.3.9")
public class IntegrationTest {
@Rule
public final TestResources resources = new TestResources();
private final MavenRuntime mavenRuntime;
public IntegrationTest(MavenRuntimeBuilder builder) throws Exception {
this.mavenRuntime = builder.build();
}
@Test
public void graph() throws Exception {
File basedir = this.resources.getBasedir("depgraph-maven-plugin-test");
MavenExecutionResult result = this.mavenRuntime
.forProject(basedir)
.execute("clean", "depgraph:graph");
result.assertErrorFreeLog();
}
}
|
Improve the naming of the variables | package org.realityforge.replicant.server.transport;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import org.realityforge.replicant.server.EntityMessage;
/**
* A simple class that collects EntityMessage instances and then
* on "completion" passes the messages to a client.
*/
public final class EntityMessageAccumulator
{
private final Map<PacketQueue, LinkedList<EntityMessage>> _changeSets = new HashMap<>();
/**
* Add a message destined for a particular packet queue.
*
* @param queue the queue.
* @param message the message.
*/
public void addEntityMessage( final PacketQueue queue, final EntityMessage message )
{
getChangeSet( queue ).add( message );
}
/**
* Complete the collection of messages and forward them to the client.
*/
public void complete()
{
for ( final Entry<PacketQueue, LinkedList<EntityMessage>> entry : _changeSets.entrySet() )
{
entry.getKey().addPacket( entry.getValue() );
}
_changeSets.clear();
}
private LinkedList<EntityMessage> getChangeSet( final PacketQueue queue )
{
LinkedList<EntityMessage> clientChangeSet = _changeSets.get( queue );
if ( null == clientChangeSet )
{
clientChangeSet = new LinkedList<>();
_changeSets.put( queue, clientChangeSet );
}
return clientChangeSet;
}
}
| package org.realityforge.replicant.server.transport;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import org.realityforge.replicant.server.EntityMessage;
/**
* A simple class that collects EntityMessage instances and then
* on "completion" passes the messages to a client.
*/
public final class EntityMessageAccumulator
{
private final Map<PacketQueue, LinkedList<EntityMessage>> _changeSets = new HashMap<>();
/**
* Add a message to a client.
*
* @param client the client/
* @param message the message.
*/
public void addEntityMessage( final PacketQueue client, final EntityMessage message )
{
getChangeSet( client ).add( message );
}
/**
* Complete the collection of messages and forward them to the client.
*/
public void complete()
{
for ( final Entry<PacketQueue, LinkedList<EntityMessage>> entry : _changeSets.entrySet() )
{
entry.getKey().addPacket( entry.getValue() );
}
_changeSets.clear();
}
private LinkedList<EntityMessage> getChangeSet( final PacketQueue info )
{
LinkedList<EntityMessage> clientChangeSet = _changeSets.get( info );
if ( null == clientChangeSet )
{
clientChangeSet = new LinkedList<>();
_changeSets.put( info, clientChangeSet );
}
return clientChangeSet;
}
}
|
Use relative imports again to support python 3 | # inbuild python imports
# inbuilt django imports
from django.test import LiveServerTestCase
# third party imports
# inter-app imports
# local imports
from . import mixins
from .mixins import SimpleTestCase
class MongoTestCase(mixins.MongoTestMixin, SimpleTestCase):
""" TestCase that creates a mongo collection and clears it after each test """
pass
class MongoLiveServerTestCase(mixins.MongoTestMixin, LiveServerTestCase):
""" TestCase that runs liveserver using mongodb instead of relational database """
pass
class Neo4jTestCase(mixins.Neo4jTestMixin, SimpleTestCase):
pass
class MongoNeo4jTestCase(mixins.MongoNeo4jTestMixin, mixins.SimpleTestCase):
pass
class RedisTestCase(mixins.RedisTestMixin, mixins.SimpleTestCase):
pass
class MongoRedisTestCase(mixins.MongoRedisTestMixin, mixins.SimpleTestCase):
pass
class RedisMongoNeo4jTestCase(mixins.RedisMongoNeo4jTestMixin, mixins.SimpleTestCase):
pass
class APIRedisTestCase(mixins.ApiTestMixin, RedisTestCase):
pass
class APIMongoTestCase(mixins.ApiTestMixin, MongoTestCase):
pass
class APINeo4jTestCase(mixins.ApiTestMixin, Neo4jTestCase):
pass
class APIMongoRedisTestCase(mixins.ApiTestMixin, MongoRedisTestCase):
pass
class APIRedisMongoNeo4jTestCase(mixins.ApiTestMixin, RedisMongoNeo4jTestCase):
pass
| # inbuild python imports
# inbuilt django imports
from django.test import LiveServerTestCase
# third party imports
# inter-app imports
# local imports
import mixins
from mixins import SimpleTestCase
class MongoTestCase(mixins.MongoTestMixin, SimpleTestCase):
""" TestCase that creates a mongo collection and clears it after each test """
pass
class MongoLiveServerTestCase(mixins.MongoTestMixin, LiveServerTestCase):
""" TestCase that runs liveserver using mongodb instead of relational database """
pass
class Neo4jTestCase(mixins.Neo4jTestMixin, SimpleTestCase):
pass
class MongoNeo4jTestCase(mixins.MongoNeo4jTestMixin, mixins.SimpleTestCase):
pass
class RedisTestCase(mixins.RedisTestMixin, mixins.SimpleTestCase):
pass
class MongoRedisTestCase(mixins.MongoRedisTestMixin, mixins.SimpleTestCase):
pass
class RedisMongoNeo4jTestCase(mixins.RedisMongoNeo4jTestMixin, mixins.SimpleTestCase):
pass
class APIRedisTestCase(mixins.ApiTestMixin, RedisTestCase):
pass
class APIMongoTestCase(mixins.ApiTestMixin, MongoTestCase):
pass
class APINeo4jTestCase(mixins.ApiTestMixin, Neo4jTestCase):
pass
class APIMongoRedisTestCase(mixins.ApiTestMixin, MongoRedisTestCase):
pass
class APIRedisMongoNeo4jTestCase(mixins.ApiTestMixin, RedisMongoNeo4jTestCase):
pass
|
Fix path resolution on the command line to support absolute paths
Before the change, I could not `codecept run /my/absolute/path`.
`path.join` would always stick the current working directory in front.
More proper path resolution is also simpler, as `path.resolve` will stick
the current working directory if the path is not already absolute. | 'use strict';
let fileExists = require('../utils').fileExists;
let output = require("../output");
let fs = require('fs');
let path = require('path');
let colors = require('colors');
module.exports.getTestRoot = function (currentPath) {
let testsPath = path.resolve(currentPath || '.');
if (!currentPath) {
output.print(`Test root is assumed to be ${colors.yellow.bold(testsPath)}`);
} else {
output.print(`Using test root ${colors.bold(testsPath)}`);
}
return testsPath;
};
module.exports.getConfig = function (testsPath) {
let configFile = path.join(testsPath, 'codecept.json');
if (!fileExists(configFile)) {
output.error(`Can not load config from ${configFile}\nCodeceptJS is not initialized in this dir. Execute 'codeceptjs init' to start`);
process.exit(1);
}
let config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
if (!config.include) config.include = {};
if (!config.helpers) config.helpers = {};
return config;
};
| 'use strict';
let fileExists = require('../utils').fileExists;
let output = require("../output");
let fs = require('fs');
let path = require('path');
let colors = require('colors');
module.exports.getTestRoot = function (currentPath) {
let testsPath = path.join(process.cwd(), currentPath || '.');
if (!currentPath) {
output.print(`Test root is assumed to be ${colors.yellow.bold(testsPath)}`);
} else {
output.print(`Using test root ${colors.bold(testsPath)}`);
}
return testsPath;
};
module.exports.getConfig = function (testsPath) {
let configFile = path.join(testsPath, 'codecept.json');
if (!fileExists(configFile)) {
output.error(`Can not load config from ${configFile}\nCodeceptJS is not initialized in this dir. Execute 'codeceptjs init' to start`);
process.exit(1);
}
let config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
if (!config.include) config.include = {};
if (!config.helpers) config.helpers = {};
return config;
};
|
Update should_write_image to return False
Update should_write_image to return False | # 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 ironic.drivers import base
class NoopStorage(base.StorageInterface):
"""No-op Storage Interface."""
def validate(self, task):
pass
def get_properties(self):
return {}
def attach_volumes(self, task):
pass
def detach_volumes(self, task):
pass
def should_write_image(self, task):
return False
| # 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 ironic.drivers import base
class NoopStorage(base.StorageInterface):
"""No-op Storage Interface."""
def validate(self, task):
pass
def get_properties(self):
return {}
def attach_volumes(self, task):
pass
def detach_volumes(self, task):
pass
def should_write_image(self, task):
return True
|
Add Odoo Community Association (OCA) as author | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Vincent Renaville
# Copyright 2015 Camptocamp SA
#
# 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/>.
#
##############################################################################
{
'name': 'Account Import Cresus',
'version': '1.0',
'depends': [
'account',
],
'author': 'Camptocamp, Odoo Community Association (OCA)',
'website': 'http://www.camptocamp.com',
'data': [
'wizard/l10n_ch_import_cresus_view.xml',
'account_tax_view.xml',
'menu.xml',
],
'installable': True,
}
| # -*- coding: utf-8 -*-
##############################################################################
#
# Author Vincent Renaville
# Copyright 2015 Camptocamp SA
#
# 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/>.
#
##############################################################################
{
'name': 'Account Import Cresus',
'version': '1.0',
'depends': [
'account',
],
'author': 'Camptocamp',
'website': 'http://www.camptocamp.com',
'data': [
'wizard/l10n_ch_import_cresus_view.xml',
'account_tax_view.xml',
'menu.xml',
],
'installable': True,
}
|
Add Wikivoyage Bengali to pywikibot
Bug: T196363
Change-Id: Ifc49b3b3734eaac20ef4f909c83d68b11bc8d91d | # -*- coding: utf-8 -*-
"""Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2018
#
# Distributed under the terms of the MIT license.
#
# The new wikivoyage family that is hosted at wikimedia
from __future__ import absolute_import, unicode_literals
from pywikibot import family
class Family(family.SubdomainFamily, family.WikimediaFamily):
"""Family class for Wikivoyage."""
name = 'wikivoyage'
languages_by_size = [
'en', 'de', 'fa', 'it', 'fr', 'pl', 'ru', 'nl', 'pt', 'zh', 'es',
'he', 'fi', 'vi', 'sv', 'el', 'ro', 'uk', 'hi', 'bn',
]
category_redirect_templates = {
'_default': (),
'zh': ('分类重定向',),
}
# Global bot allowed languages on
# https://meta.wikimedia.org/wiki/BPI#Current_implementation
# & https://meta.wikimedia.org/wiki/Special:WikiSets/2
cross_allowed = [
'el', 'en', 'es', 'fa', 'ru',
]
| # -*- coding: utf-8 -*-
"""Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2018
#
# Distributed under the terms of the MIT license.
#
# The new wikivoyage family that is hosted at wikimedia
from __future__ import absolute_import, unicode_literals
from pywikibot import family
class Family(family.SubdomainFamily, family.WikimediaFamily):
"""Family class for Wikivoyage."""
name = 'wikivoyage'
languages_by_size = [
'en', 'de', 'fa', 'it', 'fr', 'pl', 'ru', 'nl', 'pt', 'zh', 'es',
'he', 'fi', 'vi', 'sv', 'el', 'ro', 'uk', 'hi',
]
category_redirect_templates = {
'_default': (),
'zh': ('分类重定向',),
}
# Global bot allowed languages on
# https://meta.wikimedia.org/wiki/BPI#Current_implementation
# & https://meta.wikimedia.org/wiki/Special:WikiSets/2
cross_allowed = [
'el', 'en', 'es', 'fa', 'ru',
]
|
Set Devices as default view. | const routes = [
// {
// url: '#/',
// template: './routes/home/home.template.mustache',
// controller: './routes/home/home.controller',
// controllerAs: 'home'
// },
{
url: '#/login',
template: './routes/login/login.template.mustache',
controller: './routes/login/login.controller',
controllerAs: 'login'
},
{
url: '#/',
template: './routes/device/device.template.mustache',
controller: './routes/device/device.controller',
controllerAs: 'devices',
navOptions: {
title: 'Devices',
states: {
default: [ 'back', 'calendar', 'filter' ],
selected: [ 'cancel', 'edit', 'delete' ],
multipleSelected: [ 'cancel', 'delete' ]
}
}
}
];
module.exports = routes;
| const routes = [
{
url: '#/',
template: './routes/home/home.template.mustache',
controller: './routes/home/home.controller',
controllerAs: 'home'
},
{
url: '#/login',
template: './routes/login/login.template.mustache',
controller: './routes/login/login.controller',
controllerAs: 'login'
},
{
url: '#/devices',
template: './routes/device/device.template.mustache',
controller: './routes/device/device.controller',
controllerAs: 'devices',
navOptions: {
title: 'Devices',
states: {
default: [ 'back', 'calendar', 'filter' ],
selected: [ 'cancel', 'edit', 'delete' ],
multipleSelected: [ 'cancel', 'delete' ]
}
}
}
];
module.exports = routes;
|
Add StatusBar to unpkg bundle. | const Core = require('./core/index.js')
// Parent
const Plugin = require('./plugins/Plugin')
// Orchestrators
const Dashboard = require('./plugins/Dashboard/index.js')
// Acquirers
const Dummy = require('./plugins/Dummy')
const DragDrop = require('./plugins/DragDrop/index.js')
const FileInput = require('./plugins/FileInput.js')
const GoogleDrive = require('./plugins/GoogleDrive/index.js')
const Dropbox = require('./plugins/Dropbox/index.js')
const Instagram = require('./plugins/Instagram/index.js')
const Webcam = require('./plugins/Webcam/index.js')
// Progressindicators
const StatusBar = require('./plugins/StatusBar')
const ProgressBar = require('./plugins/ProgressBar.js')
const Informer = require('./plugins/Informer.js')
// Modifiers
const MetaData = require('./plugins/MetaData.js')
// Uploaders
const Tus10 = require('./plugins/Tus10')
const XHRUpload = require('./plugins/XHRUpload')
const Transloadit = require('./plugins/Transloadit')
const AwsS3 = require('./plugins/AwsS3')
module.exports = {
Core,
Plugin,
Dummy,
StatusBar,
ProgressBar,
Informer,
DragDrop,
GoogleDrive,
Dropbox,
Instagram,
FileInput,
Tus10,
XHRUpload,
Transloadit,
AwsS3,
Dashboard,
MetaData,
Webcam
}
| const Core = require('./core/index.js')
// Parent
const Plugin = require('./plugins/Plugin')
// Orchestrators
const Dashboard = require('./plugins/Dashboard/index.js')
// Acquirers
const Dummy = require('./plugins/Dummy')
const DragDrop = require('./plugins/DragDrop/index.js')
const FileInput = require('./plugins/FileInput.js')
const GoogleDrive = require('./plugins/GoogleDrive/index.js')
const Dropbox = require('./plugins/Dropbox/index.js')
const Instagram = require('./plugins/Instagram/index.js')
const Webcam = require('./plugins/Webcam/index.js')
// Progressindicators
const ProgressBar = require('./plugins/ProgressBar.js')
const Informer = require('./plugins/Informer.js')
// Modifiers
const MetaData = require('./plugins/MetaData.js')
// Uploaders
const Tus10 = require('./plugins/Tus10')
const XHRUpload = require('./plugins/XHRUpload')
const Transloadit = require('./plugins/Transloadit')
const AwsS3 = require('./plugins/AwsS3')
module.exports = {
Core,
Plugin,
Dummy,
ProgressBar,
Informer,
DragDrop,
GoogleDrive,
Dropbox,
Instagram,
FileInput,
Tus10,
XHRUpload,
Transloadit,
AwsS3,
Dashboard,
MetaData,
Webcam
}
|
Allow expressions like roll(dice(1, 4, 1)) to work | /*
* Copyright ©1998-2021 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, version 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/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.expression.function;
import com.trollworks.gcs.expression.EvaluationException;
import com.trollworks.gcs.expression.Evaluator;
import com.trollworks.gcs.utility.Dice;
import com.trollworks.gcs.utility.I18n;
public class Roll implements ExpressionFunction {
@Override
public final String getName() {
return "roll";
}
@Override
public final Object execute(Evaluator evaluator, String arguments) throws EvaluationException {
try {
Dice dice = new Dice(arguments.contains("(") ? new Evaluator(evaluator).evaluate(arguments).toString() : arguments);
return Double.valueOf(dice.roll(false));
} catch (Exception exception) {
throw new EvaluationException(String.format(I18n.text("Invalid dice specification: %s"), arguments));
}
}
}
| /*
* Copyright ©1998-2021 by Richard A. Wilkes. All rights reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, version 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/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, version 2.0.
*/
package com.trollworks.gcs.expression.function;
import com.trollworks.gcs.expression.EvaluationException;
import com.trollworks.gcs.expression.Evaluator;
import com.trollworks.gcs.utility.Dice;
import com.trollworks.gcs.utility.I18n;
public class Roll implements ExpressionFunction {
@Override
public final String getName() {
return "roll";
}
@Override
public final Object execute(Evaluator evaluator, String arguments) throws EvaluationException {
try {
Dice dice = new Dice(arguments);
return Double.valueOf(dice.roll(false));
} catch (Exception exception) {
throw new EvaluationException(String.format(I18n.text("Invalid dice specification: %s"), arguments));
}
}
}
|
Check for empty user properly | import React from 'react';
import { map, isEmpty } from 'lodash';
import { displayUserInfo, displayCityState } from '../../helpers';
const UserInformation = (props) => (
<div>
{!isEmpty(props.user) ?
<div className="container -padded">
{props.linkSignup ?
<h2 className="heading"><a href={`/signups/${props.linkSignup}`}>{displayUserInfo(props.user.first_name, props.user.last_name, props.user.birthdate)}</a></h2>
:
<h2 className="heading">{displayUserInfo(props.user.first_name, props.user.last_name, props.user.birthdate)}</h2>
}
<p>
{props.user.email ? <span>{props.user.email}<br/></span>: null}
{props.user.mobile ? <span>{props.user.mobile}<br/></span> : null }
{displayCityState(props.user.addr_city, props.user.addr_state) ? <span>{displayCityState(props.user.addr_city, props.user.addr_state) }<br/></span> : null }
</p>
</div>
:
<h2 className="heading">User Not Found</h2>
}
{props.children}
</div>
);
export default UserInformation;
| import React from 'react';
import { map } from 'lodash';
import { displayUserInfo, displayCityState } from '../../helpers';
const UserInformation = (props) => (
<div>
{props.user.length ?
<div className="container -padded">
{props.linkSignup ?
<h2 className="heading"><a href={`/signups/${props.linkSignup}`}>{displayUserInfo(props.user.first_name, props.user.last_name, props.user.birthdate)}</a></h2>
:
<h2 className="heading">{displayUserInfo(props.user.first_name, props.user.last_name, props.user.birthdate)}</h2>
}
<p>
{props.user.email ? <span>{props.user.email}<br/></span>: null}
{props.user.mobile ? <span>{props.user.mobile}<br/></span> : null }
{displayCityState(props.user.addr_city, props.user.addr_state) ? <span>{displayCityState(props.user.addr_city, props.user.addr_state) }<br/></span> : null }
</p>
</div>
:
<h2 className="heading">User Not Found</h2>
}
{props.children}
</div>
);
export default UserInformation;
|
Use DataIO2 Packed longs and ints | package com.oriordank.mapdbserializers;
import org.apache.activemq.store.PListEntry;
import org.apache.activemq.util.ByteSequence;
import org.mapdb.DataInput2;
import org.mapdb.DataOutput2;
import org.mapdb.Serializer;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;
public class PListEntrySerializer implements Serializer<PListEntry>, Serializable {
@Override
public void serialize(DataOutput out, PListEntry value) throws IOException {
out.writeUTF(value.getId());
ByteSequence bs = value.getByteSequence();
DataOutput2.packInt(out, bs.getLength());
out.write(bs.getData(), bs.getOffset(), bs.getLength());
DataOutput2.packLong(out, (Long)value.getLocator());
}
@Override
public PListEntry deserialize(DataInput in, int available) throws IOException {
String id = in.readUTF();
int length = DataInput2.unpackInt(in);
byte[] bytes = new byte[length];
in.readFully(bytes);
ByteSequence bs = new ByteSequence(bytes);
long locator = DataInput2.unpackLong(in);
PListEntry entry = new PListEntry(id, bs, locator);
return entry;
}
@Override
public int fixedSize() {
return -1;
}
}
| package com.oriordank.mapdbserializers;
import org.apache.activemq.store.PListEntry;
import org.apache.activemq.util.ByteSequence;
import org.mapdb.Serializer;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;
public class PListEntrySerializer implements Serializer<PListEntry>, Serializable {
@Override
public void serialize(DataOutput out, PListEntry value) throws IOException {
out.writeUTF(value.getId());
ByteSequence bs = value.getByteSequence();
out.writeInt(bs.getLength());
out.write(bs.getData(), bs.getOffset(), bs.getLength());
out.writeLong((Long)value.getLocator());
}
@Override
public PListEntry deserialize(DataInput in, int available) throws IOException {
String id = in.readUTF();
int length = in.readInt();
byte[] bytes = new byte[length];
in.readFully(bytes);
ByteSequence bs = new ByteSequence(bytes);
long locator = in.readLong();
PListEntry entry = new PListEntry(id, bs, locator);
return entry;
}
@Override
public int fixedSize() {
return -1;
}
}
|
Send back stderr for command-line jobs | var util = require("util");
var thunkify = require("thunkify");
var spawn = require("child_process").spawn;
var debug = require("debug")("offload:runner");
var runner = function(cmd, args, body, cb){
debug("preping job");
var envCopy = util._extend({}, process.env);
envCopy.OFFLOAD_WORKSPACE = this.workspace;
var opts = {
stdio: 'pipe',
cwd: process.cwd(),
env: envCopy
};
var jobProcess = spawn(cmd, args, opts);
debug("sending data to cmd");
//handle if body is undefined
jobProcess.stdin.write(body);
jobProcess.stdin.end();
var result = null;
jobProcess.stdout.on("data", function(data){
debug("new data received - buffer");
if (result === null) {
result = data;
}
else{
result = Buffer.concat([result, data]);
}
});
var error = "";
jobProcess.stderr.on("data", function(data){
debug("new error or warning recived");
error += data.toString();
});
jobProcess.on("exit", function(code){
if (code != 0) {
debug("job done with error");
cb({cmd:cmd, args:args, error:error});
}
else{
cb(null, result);
debug("job done");
}
});
}
module.exports = thunkify(runner);
| var util = require("util");
var thunkify = require("thunkify");
var spawn = require("child_process").spawn;
var debug = require("debug")("offload:runner");
var runner = function(cmd, args, body, cb){
debug("preping job");
var envCopy = util._extend({}, process.env);
envCopy.OFFLOAD_WORKSPACE = this.workspace;
var opts = {
stdio: 'pipe',
cwd: process.cwd(),
env: envCopy
};
var jobProcess = spawn(cmd, args, opts);
debug("sending data to cmd");
//handle if body is undefined
jobProcess.stdin.write(body);
jobProcess.stdin.end();
var result = null;
jobProcess.stdout.on("data", function(data){
debug("new data received - buffer");
if (result === null) {
result = data;
}
else{
result = Buffer.concat([result, data]);
}
});
var error = "";
jobProcess.stderr.on("data", function(data){
debug("new error or warning recived");
error += data.toString();
});
jobProcess.on("exit", function(code){
if (code != 0) {
debug("job done with error");
cb({cmd:cmd, args:args});
}
else{
cb(null, result);
debug("job done");
}
});
}
module.exports = thunkify(runner);
|
Use pack.main instead of string | const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const zlib = require('zlib');
const pack = require('../package.json');
const rootDir = path.dirname(__dirname);
const distFilePath = path.join(rootDir, pack.main);
const readmePath = path.join(rootDir, 'README.md');
const readmeDraftPath = path.join(rootDir, 'tools', 'README.draft.md');
const distFile = fs.readFileSync(distFilePath, 'utf8');
const readmeDraftFile = fs.readFileSync(readmeDraftPath, 'utf8');
const algo = 'sha384';
const size = (zlib.gzipSync(distFile).byteLength / 1024).toFixed(1);
const digest = crypto.createHash(algo).update(distFile).digest('base64');
const readme = readmeDraftFile
.replace('###gzip_size###', size)
.replace('###version###', pack.version)
.replace('###hash###', `${algo}-${digest}`);
fs.writeFileSync(readmePath, readme);
console.log(`File ${readmePath} is updated`);
console.log(`Version: ${pack.version}`);
console.log(`Hash: ${algo}-${digest}`);
console.log(`Gzip size: ${size} KiB`);
| const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const zlib = require('zlib');
const pack = require('../package.json');
const rootDir = path.dirname(__dirname);
const distFilePath = path.join(rootDir, 'dist', 'blowfish.js');
const readmePath = path.join(rootDir, 'README.md');
const readmeDraftPath = path.join(rootDir, 'tools', 'README.draft.md');
const distFile = fs.readFileSync(distFilePath, 'utf8');
const readmeDraftFile = fs.readFileSync(readmeDraftPath, 'utf8');
const algo = 'sha384';
const size = (zlib.gzipSync(distFile).byteLength / 1024).toFixed(1);
const digest = crypto.createHash(algo).update(distFile).digest('base64');
const readme = readmeDraftFile
.replace('###gzip_size###', size)
.replace('###version###', pack.version)
.replace('###hash###', `${algo}-${digest}`);
fs.writeFileSync(readmePath, readme);
console.log(`File ${readmePath} is updated`);
console.log(`Version: ${pack.version}`);
console.log(`Hash: ${algo}-${digest}`);
console.log(`Gzip size: ${size} KiB`);
|
Fix super() call for python <= 3.2 | # -*- coding: utf-8 -*-
import six
from formats import FormatBank, discover_json, discover_yaml
formats = FormatBank()
discover_json(formats, content_type='application/json')
discover_yaml(formats, content_type='application/x-yaml')
def run_from_ipython():
return getattr(__builtins__, "__IPYTHON__", False)
class Bunch(dict):
def __init__(self, kwargs=None):
if kwargs is None:
kwargs = {}
for key, value in six.iteritems(kwargs):
kwargs[key] = bunchify(value)
super(Bunch, self).__init__(kwargs)
self.__dict__ = self
def bunchify(obj):
if isinstance(obj, (list, tuple)):
return [bunchify(item) for item in obj]
if isinstance(obj, dict):
return Bunch(obj)
return obj
| # -*- coding: utf-8 -*-
import six
from formats import FormatBank, discover_json, discover_yaml
formats = FormatBank()
discover_json(formats, content_type='application/json')
discover_yaml(formats, content_type='application/x-yaml')
def run_from_ipython():
return getattr(__builtins__, "__IPYTHON__", False)
class Bunch(dict):
def __init__(self, kwargs=None):
if kwargs is None:
kwargs = {}
for key, value in six.iteritems(kwargs):
kwargs[key] = bunchify(value)
super().__init__(kwargs)
self.__dict__ = self
def bunchify(obj):
if isinstance(obj, (list, tuple)):
return [bunchify(item) for item in obj]
if isinstance(obj, dict):
return Bunch(obj)
return obj
|
Add require for global installation | <?php
if ( !defined( 'WP_CLI' ) ) return;
require_once 'src/ViewOne/Environment.php';
global $argv;
$env = $argv[1];
$config = array();
$config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml';
if ( is_readable( $config_path ) ){
$configurator = \WP_CLI::get_configurator();
$configurator->merge_yml( $config_path );
list( $config, $extra_config ) = $configurator->to_array();
}
if ( isset($config['color']) && $config['color'] === 'auto' ) {
$colorize = !\cli\Shell::isPiped();
} else {
$colorize = true;
}
if ( isset($config['quiet']) && $config['quiet'] )
$logger = new \WP_CLI\Loggers\Quiet;
else
$logger = new \WP_CLI\Loggers\Regular( $colorize );
\WP_CLI::set_logger( $logger );
try {
$environment = new \ViewOne\Environment();
$environment->run($env);
} catch (Exception $e) {
\WP_CLI::error( $e->getMessage() );
}
| <?php
if ( !defined( 'WP_CLI' ) ) return;
global $argv;
$env = $argv[1];
$config = array();
$config_path = getenv( 'HOME' ) . '/.wp-cli/config.yml';
if ( is_readable( $config_path ) ){
$configurator = \WP_CLI::get_configurator();
$configurator->merge_yml( $config_path );
list( $config, $extra_config ) = $configurator->to_array();
}
if ( isset($config['color']) && $config['color'] === 'auto' ) {
$colorize = !\cli\Shell::isPiped();
} else {
$colorize = true;
}
if ( isset($config['quiet']) && $config['quiet'] )
$logger = new \WP_CLI\Loggers\Quiet;
else
$logger = new \WP_CLI\Loggers\Regular( $colorize );
\WP_CLI::set_logger( $logger );
try {
$environment = new \ViewOne\Environment();
$environment->run($env);
} catch (Exception $e) {
\WP_CLI::error( $e->getMessage() );
}
|
feat(plugin): Manage repository as a plugin | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.plugin.core.api;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public enum PluginType {
POLICY, REPORTER, SERVICE, REPOSITORY;
public static PluginType from(String sType) {
for(PluginType pluginType : values()) {
if (pluginType.name().equalsIgnoreCase(sType)) {
return pluginType;
}
}
throw new IllegalArgumentException("Invalid PolicyType: " + sType);
}
}
| /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.plugin.core.api;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public enum PluginType {
POLICY, REPORTER, SERVICE;
public static PluginType from(String sType) {
for(PluginType pluginType : values()) {
if (pluginType.name().equalsIgnoreCase(sType)) {
return pluginType;
}
}
throw new IllegalArgumentException("Invalid PolicyType: " + sType);
}
}
|
Remove state variable where it can be removed. | import React from 'react';
import Accordion from 'react-bootstrap/Accordion';
import Card from 'react-bootstrap/Card';
import Activity from './activity';
import * as activityFns from './activityfns';
import * as utils from '../Utils/utils.js'
class ActivityDay extends React.Component {
/** @inheritdoc */
constructor(props) {
super(props);
}
/** @inheritdoc */
render() {
const sortedActivities = Array.from(this.props.activities)
.sort(activityFns.compareActivities);
let date = new Date(this.props.date);
let id = date.getTime();
return (
<Card>
<Accordion.Toggle as={Card.Header} eventKey="0" align="center" >
{utils.timestampToDateFormatted(date.getTime())}
</Accordion.Toggle>
<Accordion.Collapse eventKey="0">
<Card.Body>
{sortedActivities.map((activity, index) => (
<Activity activity={activity} key={index + id}/>
))}
</Card.Body>
</Accordion.Collapse>
</Card>
);
}
}
export default ActivityDay;
| import React from 'react';
import Accordion from 'react-bootstrap/Accordion';
import Card from 'react-bootstrap/Card';
import Activity from './activity';
import * as activityFns from './activityfns';
import * as utils from '../Utils/utils.js'
class ActivityDay extends React.Component {
/** @inheritdoc */
constructor(props) {
super(props);
this.state = {
date: props.date,
activities: Array.from(props.activities).sort(activityFns.compareActivities)
};
}
/** @inheritdoc */
render() {
let date = new Date(this.props.date);
let id = date.getTime();
return (
<Card>
<Accordion.Toggle as={Card.Header} eventKey="0" align="center" >
{utils.timestampToDateFormatted(date.getTime())}
</Accordion.Toggle>
<Accordion.Collapse eventKey="0">
<Card.Body>
{this.state.activities.map((activity, index) => (
<Activity activity={activity} key={index + id}/>
))}
</Card.Body>
</Accordion.Collapse>
</Card>
);
}
}
export default ActivityDay;
|
Fix axis domain config lookup. | import {Top, Bottom} from './constants';
import guideMark from './guide-mark';
import {RuleMark} from '../marks/marktypes';
import {AxisDomainRole} from '../marks/roles';
import {addEncode} from '../encode/encode-util';
export default function(spec, config, userEncode, dataRef) {
var orient = spec.orient,
zero = {value: 0},
encode = {}, enter, update, u, u2, v;
encode.enter = enter = {
opacity: zero
};
addEncode(enter, 'stroke', config.domainColor);
addEncode(enter, 'strokeWidth', config.domainWidth);
encode.exit = {
opacity: zero
};
encode.update = update = {
opacity: {value: 1}
};
(orient === Top || orient === Bottom)
? (u = 'x', v = 'y')
: (u = 'y', v = 'x');
u2 = u + '2',
enter[v] = zero;
update[u] = enter[u] = position(spec, 0);
update[u2] = enter[u2] = position(spec, 1);
return guideMark(RuleMark, AxisDomainRole, null, dataRef, encode, userEncode);
}
function position(spec, pos) {
return {scale: spec.scale, range: pos};
}
| import {Top, Bottom} from './constants';
import guideMark from './guide-mark';
import {RuleMark} from '../marks/marktypes';
import {AxisDomainRole} from '../marks/roles';
import {addEncode} from '../encode/encode-util';
export default function(spec, config, userEncode, dataRef) {
var orient = spec.orient,
zero = {value: 0},
encode = {}, enter, update, u, u2, v;
encode.enter = enter = {
opacity: zero
};
addEncode(enter, 'stroke', config.tickColor);
addEncode(enter, 'strokeWidth', config.tickWidth);
encode.exit = {
opacity: zero
};
encode.update = update = {
opacity: {value: 1}
};
(orient === Top || orient === Bottom)
? (u = 'x', v = 'y')
: (u = 'y', v = 'x');
u2 = u + '2',
enter[v] = zero;
update[u] = enter[u] = position(spec, 0);
update[u2] = enter[u2] = position(spec, 1);
return guideMark(RuleMark, AxisDomainRole, null, dataRef, encode, userEncode);
}
function position(spec, pos) {
return {scale: spec.scale, range: pos};
}
|
Refactor Password resetHandler handle function | <?php
namespace SumoCoders\FrameworkMultiUserBundle\Command;
use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordConfirmationException;
use SumoCoders\FrameworkMultiUserBundle\User\UserRepositoryCollection;
class PasswordResetHandler
{
/**
* @var UserRepositoryCollection
*/
private $userRepositoryCollection;
public function __construct(UserRepositoryCollection $userRepositoryCollection)
{
$this->userRepositoryCollection = $userRepositoryCollection;
}
/**
* @param ResetPassword $command
*
* @throws InvalidPasswordConfirmationException
*/
public function handle(ResetPassword $command)
{
if (!$command->passwordConfirmationIsValid()) {
throw new InvalidPasswordConfirmationException('The password confirmation isn\'t valid');
}
$user = $command->getUser();
$updatedUser = clone $user;
$updatedUser->setPassword($command->getPassword());
$updatedUser->clearPasswordResetToken();
$repository = $this->userRepositoryCollection->findRepositoryByClassName(get_class($user));
$repository->update($user, $updatedUser);
return;
}
}
| <?php
namespace SumoCoders\FrameworkMultiUserBundle\Command;
use SumoCoders\FrameworkMultiUserBundle\Exception\InvalidPasswordConfirmationException;
use SumoCoders\FrameworkMultiUserBundle\User\UserRepositoryCollection;
class PasswordResetHandler
{
/**
* @var UserRepositoryCollection
*/
private $userRepositoryCollection;
public function __construct(UserRepositoryCollection $userRepositoryCollection)
{
$this->userRepositoryCollection = $userRepositoryCollection;
}
/**
* @param ResetPassword $command
*
* @throws InvalidPasswordConfirmationException
*/
public function handle(ResetPassword $command)
{
if ($command->passwordConfirmationIsValid()) {
$user = $command->getUser();
$updatedUser = clone $user;
$updatedUser->setPassword($command->getPassword());
$updatedUser->clearPasswordResetToken();
$repository = $this->userRepositoryCollection->findRepositoryByClassName(get_class($user));
$repository->update($user, $updatedUser);
return;
}
throw new InvalidPasswordConfirmationException('The password confirmation isn\'t valid');
}
}
|
Use Ember alias for jQuery | import Ember from 'ember';
import ENV from '../config/environment';
export function initialize() {
Ember.$.getScript('//js.honeybadger.io/v0.2/honeybadger.min.js').then(function() {
if (window.Honeybadger) {
var apiKey = Ember.get(ENV, 'honeybadger.apiKey');
var environment = Ember.get(ENV, 'honeybadger.environment');
var debug = Ember.get(ENV, 'honeybadger.debug') || false;
window.Honeybadger.configure({
api_key: apiKey,
environment: environment,
debug: debug,
onerror: true
});
}
});
}
export default {
name: 'honeybadger',
initialize: initialize
};
| import Ember from 'ember';
import ENV from '../config/environment';
export function initialize() {
$.getScript('//js.honeybadger.io/v0.2/honeybadger.min.js').then(function() {
if (window.Honeybadger) {
var apiKey = Ember.get(ENV, 'honeybadger.apiKey');
var environment = Ember.get(ENV, 'honeybadger.environment');
var debug = Ember.get(ENV, 'honeybadger.debug') || false;
window.Honeybadger.configure({
api_key: apiKey,
environment: environment,
debug: debug,
onerror: true
});
}
});
}
export default {
name: 'honeybadger',
initialize: initialize
}; |
Remove thunk add canvas middleware | import { createStore, applyMiddleware, compose } from 'redux';
import { persistState } from 'redux-devtools';
import rootReducer from '../reducers';
import DevTools from '../dev/dev_tools.jsx'
import API from '../middleware/api';
import CanvasApi from '../middleware/canvas_api';
let middleware = [ API, CanvasApi ];
let enhancers = [
applyMiddleware(...middleware)
];
// In production, we want to use just the middleware.
// In development, we want to use some store enhancers from redux-devtools.
// UglifyJS will eliminate the dead code depending on the build environment.
if (__DEV__){
enhancers = [
...enhancers,
DevTools.instrument(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
];
}
export default function(initialState){
const store = compose(...enhancers)(createStore)(rootReducer, initialState);
if (__DEV__ && module.hot) {
module.hot.accept(
'../reducers',
() => store.replaceReducer(require('../reducers'))
);
}
return store;
}
| import { createStore, applyMiddleware, compose } from 'redux';
import { persistState } from 'redux-devtools';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
import DevTools from '../dev/dev_tools.jsx'
import API from '../middleware/api';
let middleware = [ thunk, API ];
let enhancers = [
applyMiddleware(...middleware)
];
// In production, we want to use just the middleware.
// In development, we want to use some store enhancers from redux-devtools.
// UglifyJS will eliminate the dead code depending on the build environment.
if (__DEV__){
enhancers = [
...enhancers,
DevTools.instrument(),
persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
];
}
export default function(initialState){
const store = compose(...enhancers)(createStore)(rootReducer, initialState);
if (__DEV__ && module.hot) {
module.hot.accept(
'../reducers',
() => store.replaceReducer(require('../reducers'))
);
}
return store;
}
|
CC-5781: Upgrade script for new storage quota implementation
Upgrade script for saas only | <?php
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByType('stor')
->filterByExists(true)
->findOne();
$storPath = $musicDir->getDirectory();
$f = $storPath;
$io = popen('/usr/bin/du -bs ' . $f, 'r');
$size = fgets($io, 4096);
$size = substr($size, 0, strpos($size, "\t"));
pclose($io);
Application_Model_Preference::setDiskUsage($size);
}
}
| <?php
class StorageQuotaUpgrade
{
public static function startUpgrade()
{
echo "* Updating storage usage for new quota tracking".PHP_EOL;
self::setStorageUsage();
}
private static function setStorageUsage()
{
$musicDir = CcMusicDirsQuery::create()
->filterByType('stor')
->filterByExists(true)
->findOne();
$storPath = $musicDir->getDirectory();
$freeSpace = disk_free_space($storPath);
$totalSpace = disk_total_space($storPath);
Application_Model_Preference::setDiskUsage($totalSpace - $freeSpace);
}
}
|
Implement fix for Open Flash Chart not displaying in Firefox.
Tom
git-svn-id: ec090d62484f5211934fcf70a1de07e1dda17a57@56 c3eb156b-1dc0-44e1-88ae-e38439141b53 | <?php
$this->load->view("partial/header");
?>
<div id="page_title" style="margin-bottom:8px;"><?php echo $title ?></div>
<div id="page_subtitle" style="margin-bottom:8px;"><?php echo $subtitle ?></div>
<div style="text-align: center;">
<script type="text/javascript">
swfobject.embedSWF(
"<?php echo base_url(); ?>open-flash-chart.swf", "chart",
"800", "400", "9.0.0", "expressInstall.swf",
{"data-file":"<?php echo $data_file; ?>"} )
</script>
<?php
?>
</div>
<div id="chart_wrapper">
<div id="chart"></div>
</div>
<div id="report_summary">
<?php foreach($summary_data as $name=>$value) { ?>
<div class="summary_row"><?php echo $this->lang->line('reports_'.$name). ': '.to_currency($value); ?></div>
<?php }?>
</div>
<?php
$this->load->view("partial/footer");
?> | <?php
$this->load->view("partial/header");
?>
<div id="page_title" style="margin-bottom:8px;"><?php echo $title ?></div>
<div id="page_subtitle" style="margin-bottom:8px;"><?php echo $subtitle ?></div>
<div style="text-align: center;">
<script type="text/javascript">
swfobject.embedSWF(
"<?php echo base_url(); ?>open-flash-chart.swf", "chart",
"100%", "100%", "9.0.0", "expressInstall.swf",
{"data-file":"<?php echo $data_file; ?>"} )
</script>
<?php
?>
</div>
<div id="chart_wrapper">
<div id="chart"></div>
</div>
<div id="report_summary">
<?php foreach($summary_data as $name=>$value) { ?>
<div class="summary_row"><?php echo $this->lang->line('reports_'.$name). ': '.to_currency($value); ?></div>
<?php }?>
</div>
<?php
$this->load->view("partial/footer");
?> |
Fix pep8 order import issue | # 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 ConfigParser
import json
import falcon
class _SimpleResource(object):
def __init__(self, conf):
try:
message = conf.get('sample_app', 'message')
except ConfigParser.Error:
message = 'something'
self._message = message
def on_get(self, req, resp):
resp.body = json.dumps({'message': self._message})
resp.set_header('Content-Type', 'application/json')
def on_put(self, req, resp):
doc = json.load(req.stream)
self._message = doc['message']
resp.body = json.dumps({'message': self._message})
def make_application():
conf = ConfigParser.RawConfigParser()
conf.read(['/etc/sample_app/sample_app.conf'])
application = falcon.API()
application.add_route('/', _SimpleResource(conf))
return application
| # 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 json
import ConfigParser
import falcon
class _SimpleResource(object):
def __init__(self, conf):
try:
message = conf.get('sample_app', 'message')
except ConfigParser.Error:
message = 'something'
self._message = message
def on_get(self, req, resp):
resp.body = json.dumps({'message': self._message})
resp.set_header('Content-Type', 'application/json')
def on_put(self, req, resp):
doc = json.load(req.stream)
self._message = doc['message']
resp.body = json.dumps({'message': self._message})
def make_application():
conf = ConfigParser.RawConfigParser()
conf.read(['/etc/sample_app/sample_app.conf'])
application = falcon.API()
application.add_route('/', _SimpleResource(conf))
return application
|
Add json as a keyword. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
'python-dateutil',
'sdag2',
'six'
]
test_requirements = [
]
setup(
name='jsonte',
version='0.8.5',
description="Json Type Extensions.",
long_description=readme + '\n\n' + history,
author="Rasjid Wilcox",
author_email='rasjidw@openminddev.net',
url='https://github.com/rasjidw/python-jsonte',
py_modules=['jsonte'],
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='jsonte json',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
test_suite='test_jsonte',
tests_require=test_requirements
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read().replace('.. :changelog:', '')
requirements = [
'python-dateutil',
'sdag2',
'six'
]
test_requirements = [
]
setup(
name='jsonte',
version='0.8.5',
description="Json Type Extensions.",
long_description=readme + '\n\n' + history,
author="Rasjid Wilcox",
author_email='rasjidw@openminddev.net',
url='https://github.com/rasjidw/python-jsonte',
py_modules=['jsonte'],
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='jsonte',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
test_suite='test_jsonte',
tests_require=test_requirements
)
|
Use bufio.Writer instead of io.Writer & bytes.Buffer
name old time/op new time/op delta
Terminal-4 1.69µs ± 2% 1.64µs ± 1% -2.69% (p=0.000 n=9+10) | package terminal
import (
"bufio"
"io"
"strconv"
"github.com/mattn/go-runewidth"
)
type Terminal struct {
w *bufio.Writer
msg string
}
func New(w io.Writer) *Terminal {
return &Terminal{
w: bufio.NewWriterSize(w, 32),
}
}
func (t *Terminal) Refresh(prompt string, s []rune, pos int) {
t.w.WriteString("\r\033[J")
t.w.WriteString(prompt)
t.w.WriteString(string(s))
if t.msg != "" {
t.w.WriteString("\n")
t.w.WriteString(t.msg)
t.w.WriteString("\033[A")
}
t.w.WriteString("\033[")
t.w.WriteString(strconv.Itoa(runewidth.StringWidth(prompt) + runesWidth(s[:pos]) + 1))
t.w.WriteString("G")
t.w.Flush()
}
func runesWidth(s []rune) (width int) {
for _, r := range s {
width += runewidth.RuneWidth(r)
}
return width
}
func (t *Terminal) SetLastLine(msg string) {
t.msg = msg
}
| package terminal
import (
"bytes"
"io"
"strconv"
"github.com/mattn/go-runewidth"
)
type Terminal struct {
w io.Writer
buf *bytes.Buffer
msg string
}
func New(w io.Writer) *Terminal {
return &Terminal{
w: w,
buf: bytes.NewBuffer(make([]byte, 0, 32)),
}
}
func (t *Terminal) Refresh(prompt string, s []rune, pos int) {
t.buf.WriteString("\r\033[J")
t.buf.WriteString(prompt)
t.buf.WriteString(string(s))
if t.msg != "" {
t.buf.WriteString("\n")
t.buf.WriteString(t.msg)
t.buf.WriteString("\033[A")
}
t.buf.WriteString("\033[")
t.buf.WriteString(strconv.Itoa(runewidth.StringWidth(prompt) + runesWidth(s[:pos]) + 1))
t.buf.WriteString("G")
t.buf.WriteTo(t.w)
}
func runesWidth(s []rune) (width int) {
for _, r := range s {
width += runewidth.RuneWidth(r)
}
return width
}
func (t *Terminal) SetLastLine(msg string) {
t.msg = msg
}
|
Use online CDN for DOK | // For any third party dependencies, like jQuery, place them in the lib folder.
// Configure loading modules from the lib directory,
// except for 'app' ones, which are in a sibling
// directory.
requirejs.config({
// enforceDefine: true,
baseUrl: 'scripts/lib',
paths: {
jquery: 'https://code.jquery.com/jquery-3.2.1.slim.min',
lodash: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min',
seedRandom: 'https://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.3/seedrandom.min',
threejs: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min',
dobuki: 'https://jacklehamster.github.io/dok/out/dok.min',
jsgif: 'jsgif/gif'
},
urlArgs: "bust=" + Date.now(),
catchError:false,
});
define(function() {
// Start loading the main app file. Put all of
// your application logic in there.
requirejs(['scripts/main.js']);
});
| // For any third party dependencies, like jQuery, place them in the lib folder.
// Configure loading modules from the lib directory,
// except for 'app' ones, which are in a sibling
// directory.
requirejs.config({
// enforceDefine: true,
baseUrl: 'scripts/lib',
paths: {
jquery: 'https://code.jquery.com/jquery-3.2.1.slim.min',
lodash: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min',
seedRandom: 'https://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.3/seedrandom.min',
threejs: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/85/three.min',
dobuki: 'dok/dobuki',
jsgif: 'jsgif/gif'
},
urlArgs: "bust=" + Date.now(),
catchError:false,
});
define(function() {
// Start loading the main app file. Put all of
// your application logic in there.
requirejs(['scripts/main.js']);
});
|
Send the query over to plone in the proper format. | <?php
#
# Copyright (c) 2000-2013 University of Utah and the Flux Group.
#
# {{{EMULAB-LICENSE
#
# This file is part of the Emulab network testbed software.
#
# This file 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 file 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 file. If not, see <http://www.gnu.org/licenses/>.
#
# }}}
#
require("defs.php3");
#
# Verify page arguments.
#
$optargs = OptionalPageArguments("submit", PAGEARG_STRING,
"query", PAGEARG_STRING);
if (!isset($query) || $query == "Search Documentation") {
$query = "";
}
else {
$query = urldecode($query);
$query = preg_replace("/[\ ]+/", "+", $query);
}
header("Location: http://wiki.emulab.net/@@search?SearchableText=$query");
?>
| <?php
#
# Copyright (c) 2000-2013 University of Utah and the Flux Group.
#
# {{{EMULAB-LICENSE
#
# This file is part of the Emulab network testbed software.
#
# This file 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 file 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 file. If not, see <http://www.gnu.org/licenses/>.
#
# }}}
#
require("defs.php3");
#
# Verify page arguments.
#
$optargs = OptionalPageArguments("submit", PAGEARG_STRING,
"query", PAGEARG_STRING);
if (!isset($query) || $query == "Search Documentation") {
$query = "";
}
header("Location: http://wiki.emulab.net/@@search?SearchableText=$query");
?>
|
Remove empty line between godoc and package declaration | // Copyright 2017 Pilosa Corp.
//
// 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.
//
//go:generate statik -src=../webui -dest=..
//
// Package statik contains static assets for the Web UI. `go generate` or
// `make generate-statik` will produce statik.go, which is ignored by git.
package statik
import (
"net/http"
"github.com/pilosa/pilosa"
"github.com/rakyll/statik/fs"
)
// Ensure nopFileSystem implements interface.
var _ pilosa.FileSystem = &FileSystem{}
// FileSystem represents a static FileSystem.
type FileSystem struct{}
// New is a statik implementation of FileSystem New method.
func (s *FileSystem) New() (http.FileSystem, error) {
return fs.New()
}
| // Copyright 2017 Pilosa Corp.
//
// 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.
//
//go:generate statik -src=../webui -dest=..
//
// Package statik contains static assets for the Web UI. `go generate` or
// `make generate-statik` will produce statik.go, which is ignored by git.
package statik
import (
"net/http"
"github.com/pilosa/pilosa"
"github.com/rakyll/statik/fs"
)
// Ensure nopFileSystem implements interface.
var _ pilosa.FileSystem = &FileSystem{}
// FileSystem represents a static FileSystem.
type FileSystem struct{}
// New is a statik implementation of FileSystem New method.
func (s *FileSystem) New() (http.FileSystem, error) {
return fs.New()
}
|
Update Russian translation by Sanek | /* Russian translation for the jQuery Timepicker Addon */
/* Written by Trent Richardson */
(function($) {
$.timepicker.regional['ru'] = {
timeOnlyTitle: 'Выберите время',
timeText: 'Время',
hourText: 'Часы',
minuteText: 'Минуты',
secondText: 'Секунды',
millisecText: 'Миллисекунды',
timezoneText: 'Часовой пояс',
currentText: 'Сейчас',
closeText: 'Закрыть',
timeFormat: 'hh:mm tt',
amNames: ['AM', 'A'],
pmNames: ['PM', 'P'],
ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['ru']);
})(jQuery);
| /* Russian translation for the jQuery Timepicker Addon */
/* Written by Trent Richardson */
(function($) {
$.timepicker.regional['ru'] = {
timeOnlyTitle: 'Выберите время',
timeText: 'Время',
hourText: 'Часы',
minuteText: 'Минуты',
secondText: 'Секунды',
millisecText: 'Миллисекунды',
timezoneText: 'Время зоны',
currentText: 'Теперь',
closeText: 'Закрыть',
timeFormat: 'hh:mm tt',
amNames: ['AM', 'A'],
pmNames: ['PM', 'P'],
ampm: false
};
$.timepicker.setDefaults($.timepicker.regional['ru']);
})(jQuery);
|
Fix typo on sound sensor example | # GrovePi + Sound Sensor + LED
# http://www.seeedstudio.com/wiki/Grove_-_Sound_Sensor
# http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
import time
import grovepi
# Connect the Sound Sensor to analog port A0
sound_sensor = 0
# Connect the LED to digital port D5
led = 5
grovepi.pinMode(sound_sensor,"INPUT")
grovepi.pinMode(led,"OUTPUT")
# The threshold to turn the led on 400.00 * 5 / 1024 = 1.95v
threshold_value = 400
while True:
try:
# Read the sound level
sensor_value = grovepi.analogRead(sound_sensor)
print sensor_value
# If loud, illuminate LED, otherwise dim
if sensor_value > threshold_value:
grovepi.digitalWrite(led,1)
else:
grovepi.digitalWrite(led,0)
time.sleep(.5)
except IOError:
print "Error"
| # GrovePi + Sound Sensor + LED
# http://www.seeedstudio.com/wiki/Grove_-_Sound_Sensor
# http://www.seeedstudio.com/wiki/Grove_-_LED_Socket_Kit
import time
import grovepi
# Connect the Sound Sensor to analog port A0
sound_sensor = 0
# Connect the LED to digital port D5
led = 5
grovepi.pinMode(sound_sensor,"INPUT")
grovepi.pinMode(led,"OUTPUT")
# The threshold to turn the led on 400.00 * 5 / 1024 = 1.95v
threshold_value = 400
while True:
try:
# Read the sound level
sensor_value = grovepi.analogRead(sound_sensor)
print sensor_value
# If loud, illuminate LED, otherwise dim
if sensor_value > threshold_value
grovepi.digitalWrite(led,1)
else:
grovepi.digitalWrite(led,0)
time.sleep(.5)
except IOError:
print "Error"
|
Use inRemote to implement forCurrentPR | const NULL = Symbol('null');
export default class Search {
constructor(name, query, attrs = {}) {
this.name = name;
this.query = query;
this.attrs = attrs;
}
getName() {
return this.name;
}
createQuery() {
return this.query;
}
// A null search has insufficient information to construct a canned query, so it should always return no results.
isNull() {
return this.attrs[NULL] || false;
}
static forCurrentPR(remote, branch) {
const name = 'Current pull request';
const upstream = branch.getUpstream();
if (!upstream.isRemoteTracking()) {
return new this(name, '', {[NULL]: true});
}
return this.inRemote(remote, name, `type:pr head:${upstream.getShortRemoteRef()}`);
}
static inRemote(remote, name, query) {
if (!remote.isGithubRepo()) {
return new this(name, '', {[NULL]: true});
}
return new this(name, `repo:${remote.getOwner()}/${remote.getRepo()} ${query.trim()}`);
}
}
| const NULL = Symbol('null');
export default class Search {
constructor(name, query, attrs = {}) {
this.name = name;
this.query = query;
this.attrs = attrs;
}
getName() {
return this.name;
}
createQuery() {
return this.query;
}
// A null search has insufficient information to construct a canned query, so it should always return no results.
isNull() {
return this.attrs[NULL] || false;
}
static forCurrentPR(remote, branch) {
const name = 'Current pull request';
const upstream = branch.getUpstream();
if (!remote.isPresent() || !remote.isGithubRepo() || !upstream.isRemoteTracking()) {
return new this(name, '', {[NULL]: true});
}
return new this(name, `repo:${remote.getOwner()}/${remote.getRepo()} type:pr head:${upstream.getShortRemoteRef()}`);
}
static inRemote(remote, name, query) {
if (!remote.isPresent()) {
return new this(name, '', {[NULL]: true});
}
return new this(name, `repo:${remote.getOwner()}/${remote.getRepo()} ${query.trim()}`);
}
}
|
Fix a bug: Called getTime on date that couldn't be parsed. | import chrono from 'chrono-node'
const BEFORE_REGEX = /before "(.*?)"/
const AFTER_REGEX = /after "(.*?)"/
// Takes in query as a string and extracts startDate and endDate
export default function extractTimeFiltersFromQuery(query) {
const matchedBefore = query.match(BEFORE_REGEX)
const matchedAfter = query.match(AFTER_REGEX)
let startDate
let endDate
if (matchedBefore && matchedBefore[1]) {
const parsedDate = chrono.parseDate(matchedBefore[1])
endDate = parsedDate && parsedDate.getTime()
}
if (matchedAfter && matchedAfter[1]) {
const parsedDate = chrono.parseDate(matchedAfter[1])
startDate = parsedDate && parsedDate.getTime()
}
// Checks which comes first before/after and based on that decide where query should be sliced
const firstIndexOfTimeFilter = Math.min(
matchedBefore ? matchedBefore.index : query.length,
matchedAfter ? matchedAfter.index : query.length,
)
const extractedQuery = query.substring(0, firstIndexOfTimeFilter)
return {
startDate,
endDate,
extractedQuery,
}
}
| import chrono from 'chrono-node'
const BEFORE_REGEX = /before "(.*?)"/
const AFTER_REGEX = /after "(.*?)"/
// Takes in query as a string and extracts startDate and endDate
export default function extractTimeFiltersFromQuery(query) {
const matchedBefore = query.match(BEFORE_REGEX)
const matchedAfter = query.match(AFTER_REGEX)
let startDate
let endDate
if (matchedBefore && matchedBefore[1]) endDate = chrono.parseDate(matchedBefore[1]).getTime()
if (matchedAfter && matchedAfter[1]) startDate = chrono.parseDate(matchedAfter[1]).getTime()
// Checks which comes first before/after and based on that decide where query should be sliced
const firstIndexOfTimeFilter = Math.min(
matchedBefore ? matchedBefore.index : query.length,
matchedAfter ? matchedAfter.index : query.length,
)
const extractedQuery = query.substring(0, firstIndexOfTimeFilter)
return {
startDate,
endDate,
extractedQuery,
}
}
|
Make unit test class abstract | <?php
abstract class UnitTest {
public $assertCount = 0;
public $passCount = 0;
public function assertTrue( $condition, $description = '' ) {
++$this->assertCount;
if ( !$condition ) {
throw new UnitTestFailedException( $description );
}
++$this->passCount;
}
public function assertEquals( $expected, $actual, $description = '' ) {
if ( $description != '' ) {
$description .= '. ';
}
$description .= "Expected '$expected', found '$actual'.";
$this->assertTrue( $expected === $actual, $description );
}
public function setUp() {
$tables = dbListTables();
foreach ( $tables as $table ) {
db( 'TRUNCATE TABLE ' . $table );
}
}
}
class UnitTestFailedException extends Exception {}
?>
| <?php
class UnitTest {
public $assertCount = 0;
public $passCount = 0;
public function assertTrue( $condition, $description = '' ) {
++$this->assertCount;
if ( !$condition ) {
throw new UnitTestFailedException( $description );
}
++$this->passCount;
}
public function assertEquals( $expected, $actual, $description = '' ) {
if ( $description != '' ) {
$description .= '. ';
}
$description .= "Expected '$expected', found '$actual'.";
$this->assertTrue( $expected === $actual, $description );
}
public function setUp() {
$tables = dbListTables();
foreach ( $tables as $table ) {
db( 'TRUNCATE TABLE ' . $table );
}
}
}
class UnitTestFailedException extends Exception {}
?>
|
Fix Serializer locking bug that caused it to skip calls it should have made | #
# Copyright (c) SAS Institute 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.
#
from twisted.internet import defer
class Serializer(object):
def __init__(self):
self._lock = defer.DeferredLock()
self._waiting = {}
def call(self, func, args=(), kwargs=None, collapsible=False):
d = self._lock.acquire()
self._waiting[d] = collapsible
if not kwargs:
kwargs = {}
@d.addCallback
def _locked(_):
if collapsible and len(self._waiting) > 1:
# Superseded
return
return func(*args, **kwargs)
@d.addBoth
def _unlock(result):
del self._waiting[d]
self._lock.release()
return result
return d
| #
# Copyright (c) SAS Institute 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.
#
from twisted.internet import defer
class Serializer(object):
def __init__(self):
self._lock = defer.DeferredLock()
self._waiting = {}
def call(self, func, args=(), kwargs=None, collapsible=False):
d = self._lock.acquire()
self._waiting[d] = collapsible
if not kwargs:
kwargs = {}
@d.addCallback
def _locked(_):
if collapsible and len(self._waiting) > 1:
# Superseded
return
return func(*args, **kwargs)
@d.addBoth
def _unlock(result):
self._lock.release()
del self._waiting[d]
return result
return d
|
Change timeout for test python_buildpack Procfile
The Python apps take longer to stage. We found out that the current
`cf start` for the python buildpack test is timing out, specially
when running the test.
That is very likely due the multiple nodes causing load on the platform.
To reduce the number of failures, we will increase the timeout by using
CF_PUSH_TIMEOUT (2 minutes) instead of DEFAULT_TIMEOUT*2 (1 minute) in
the `cf start` of the python app. | package acceptance_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
"github.com/cloudfoundry-incubator/cf-test-helpers/generator"
)
var _ = Describe("PythonBuildpack", func() {
var (
appName string
)
It("should not fail when pushing a python app without Procfile", func() {
appName = generator.PrefixedRandomName("CATS-APP-")
Expect(cf.Cf(
"push", appName,
"--no-start",
"-m", DEFAULT_MEMORY_LIMIT,
"-p", "../../example-apps/simple-python-app",
"-b", "python_buildpack",
"-c", "python hello.py",
"-d", config.AppsDomain,
).Wait(CF_PUSH_TIMEOUT)).To(Exit(0))
Expect(cf.Cf("start", appName).Wait(CF_PUSH_TIMEOUT)).To(Exit(0))
})
})
| package acceptance_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
"github.com/cloudfoundry-incubator/cf-test-helpers/generator"
)
var _ = Describe("PythonBuildpack", func() {
var (
appName string
)
It("should not fail when pushing a python app without Procfile", func() {
appName = generator.PrefixedRandomName("CATS-APP-")
Expect(cf.Cf(
"push", appName,
"--no-start",
"-m", DEFAULT_MEMORY_LIMIT,
"-p", "../../example-apps/simple-python-app",
"-b", "python_buildpack",
"-c", "python hello.py",
"-d", config.AppsDomain,
).Wait(CF_PUSH_TIMEOUT)).To(Exit(0))
Expect(cf.Cf("start", appName).Wait(DEFAULT_TIMEOUT * 2)).To(Exit(0))
})
})
|
Add tabIndex and alt for Aria. | import React from 'react';
import WeatherIcons from '../weather_icons/WeatherIcons'
const SevenHour = ({hourlyForecast}) => {
if(!hourlyForecast){
return(
<div></div>
)
}
const icons = new WeatherIcons();
const sevenHourForecast = hourlyForecast.slice(0, 7)
const sevenHourDataLoop = sevenHourForecast.map((hour, i) => {
return(
<div key={i} className="hourly-box">
<h2 className="hourly-forecast hourly-time" tabIndex="0">{hour.FCTTIME.civil}</h2>
<h6 className={`hourly-icon ${icons[hour.icon]}`} tabIndex="0" alt="hourly weather icon" aria-label="hourly weather icon"></h6>
<h2 className="hourly-forecast hourly-temp" tabIndex="0">{hour.temp.english}°F</h2>
</div>
);
})
return(
<section className="seven-hour-container">
{sevenHourDataLoop}
</section>
)
}
export default SevenHour;
| import React from 'react';
import WeatherIcons from '../weather_icons/WeatherIcons'
const SevenHour = ({hourlyForecast}) => {
if(!hourlyForecast){
return(
<div></div>
)
}
const icons = new WeatherIcons();
const sevenHourForecast = hourlyForecast.slice(0, 7)
const sevenHourDataLoop = sevenHourForecast.map((hour, i) => {
return(
<div key={i} className="hourly-box">
<h2 className="hourly-forecast hourly-time">{hour.FCTTIME.civil}</h2>
<h6 className={`hourly-icon ${icons[hour.icon]}`}></h6>
<h2 className="hourly-forecast hourly-temp">{hour.temp.english}°F</h2>
</div>
);
})
return(
<section className="seven-hour-container">
{sevenHourDataLoop}
</section>
)
}
export default SevenHour;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.