text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Add newlines between file contents | var fs = require('fs'),
path = require('path');
function stripExports(string) {
var match = string.match(/\/\/ <browser>([\s\S]*)\/\/ <\/browser>/);
return (match ? match[1] : string).replace(/^\s*|\s*$/g, '');
}
function bundle(root) {
var files = [
'base.js', 'parser.js.client', 'expression.js', 'ast.js',
'compiler.js'
],
lib = '/lib/temple/',
out = '';
files.forEach(function (file) {
file = fs.readFileSync(path.join(root, lib, file), 'utf-8');
out += stripExports(file) + '\n\n';
});
console.log(out);
}
bundle(process.cwd());
| var fs = require('fs'),
path = require('path');
function stripExports(string) {
var match = string.match(/\/\/ <browser>([\s\S]*)\/\/ <\/browser>/);
return (match ? match[1] : string).replace(/^\s*|\s*$/g, '');
}
function bundle(root) {
var files = [
'base.js', 'parser.js.client', 'expression.js', 'ast.js',
'compiler.js'
],
lib = '/lib/temple/',
out = '';
files.forEach(function (file) {
file = fs.readFileSync(path.join(root, lib, file), 'utf-8');
out += stripExports(file);
});
console.log(out);
}
bundle(process.cwd());
|
Fix typo in help text | const messageHelpers = require('../lib/message_helpers');
const handler = async function(message) {
const args = message.content.split(' ').slice(1);
// the first argument is non-optional, fail if not provided
if (args.length < 1) {
await messageHelpers.sendError(message,
'You must specify a number of messages to be deleted');
return;
}
const n = Number(args[0]);
if (isNaN(n)) {
await messageHelpers.sendError(message, `Invalid argument for n: ${n}`);
return;
}
// the user must be in a channel for this command to be useful
if (!message.channel) {
await messageHelpers.sendError(message,
`You must send this command from a channel for it to be useful`);
return;
}
// delete the messages
await message.channel.bulkDelete(n);
await message.delete();
};
module.exports = {
bind: 'purge',
handler: handler,
help: 'Purge the last <n> messages from the channel this command' +
' is invoked in.',
administrative: true,
};
| const messageHelpers = require('../lib/message_helpers');
const handler = async function(message) {
const args = message.content.split(' ').slice(1);
// the first argument is non-optional, fail if not provided
if (args.length < 1) {
await messageHelpers.sendError(message,
'You must specify a number of messages to be deleted');
return;
}
const n = Number(args[0]);
if (isNaN(n)) {
await messageHelpers.sendError(message, `Invalid argument for n: ${n}`);
return;
}
// the user must be in a channel for this command to be useful
if (!message.channel) {
await messageHelpers.sendError(message,
`You must send this command from a channel for it to be useful`);
return;
}
// delete the messages
await message.channel.bulkDelete(n);
await message.delete();
};
module.exports = {
bind: 'purge',
handler: handler,
help: 'Purge the last <n> messages from the channel this command' +
'is invoked in.',
administrative: true,
};
|
Set integration type to dropin2 | 'use strict';
module.exports = {
paymentOptionIDs: {
card: 'card',
paypal: 'paypal'
},
paymentMethodTypes: {
card: 'CreditCard',
paypal: 'PayPalAccount'
},
analyticsKinds: {
CreditCard: 'card',
PayPalAccount: 'paypal'
},
paymentMethodCardTypes: {
Visa: 'visa',
MasterCard: 'master-card',
'American Express': 'american-express',
'Diners Club': 'diners-club',
Discover: 'discover',
JCB: 'jcb',
UnionPay: 'unionpay',
Maestro: 'maestro'
},
configurationCardTypes: {
visa: 'Visa',
'master-card': 'MasterCard',
'american-express': 'American Express',
'diners-club': 'Discover',
discover: 'Discover',
jcb: 'JCB',
unionpay: 'UnionPay',
maestro: 'Maestro'
},
errors: {
NO_PAYMENT_METHOD_ERROR: 'No payment method is available.'
},
ANALYTICS_REQUEST_TIMEOUT_MS: 2000,
ANALYTICS_PREFIX: 'web.dropin.',
INTEGRATION: 'dropin2',
STYLESHEET_ID: 'braintree-dropin-stylesheet'
};
| 'use strict';
module.exports = {
paymentOptionIDs: {
card: 'card',
paypal: 'paypal'
},
paymentMethodTypes: {
card: 'CreditCard',
paypal: 'PayPalAccount'
},
analyticsKinds: {
CreditCard: 'card',
PayPalAccount: 'paypal'
},
paymentMethodCardTypes: {
Visa: 'visa',
MasterCard: 'master-card',
'American Express': 'american-express',
'Diners Club': 'diners-club',
Discover: 'discover',
JCB: 'jcb',
UnionPay: 'unionpay',
Maestro: 'maestro'
},
configurationCardTypes: {
visa: 'Visa',
'master-card': 'MasterCard',
'american-express': 'American Express',
'diners-club': 'Discover',
discover: 'Discover',
jcb: 'JCB',
unionpay: 'UnionPay',
maestro: 'Maestro'
},
errors: {
NO_PAYMENT_METHOD_ERROR: 'No payment method is available.'
},
ANALYTICS_REQUEST_TIMEOUT_MS: 2000,
ANALYTICS_PREFIX: 'web.dropin.',
INTEGRATION: 'dropin',
STYLESHEET_ID: 'braintree-dropin-stylesheet'
};
|
Put private methods on top. | 'use strict';
var google = global.google;
function positionOverlayByDimensions(projectedLatLng) {
var offsetHeight = this.el.offsetHeight,
offsetWidth = this.el.offsetWidth;
this.el.style.top = projectedLatLng.y - offsetHeight + 'px';
this.el.style.left = projectedLatLng.x - Math.floor(offsetWidth / 2) + 'px';
}
function draw() {
var projection = this.getProjection(),
projectedLatLng = projection.fromLatLngToDivPixel(this.point);
positionOverlayByDimensions.call(this, projectedLatLng);
}
function onAdd() {
var panes = this.getPanes();
panes.overlayLayer.appendChild(this.el);
}
function BaseOverlay(options) {
var point = options.point;
this.el = options.el;
this.point = new google.maps.LatLng(point.lat, point.lng);
this.el.style.position = 'absolute';
}
BaseOverlay.prototype = Object.create(google.maps.OverlayView.prototype);
BaseOverlay.prototype.constructor = BaseOverlay;
BaseOverlay.prototype.onAdd = onAdd;
BaseOverlay.prototype.draw = draw;
module.exports = BaseOverlay;
| 'use strict';
var google = global.google;
function onAdd() {
var panes = this.getPanes();
panes.overlayLayer.appendChild(this.el);
}
function positionOverlayByDimensions(projectedLatLng) {
var offsetHeight = this.el.offsetHeight,
offsetWidth = this.el.offsetWidth;
this.el.style.top = projectedLatLng.y - offsetHeight + 'px';
this.el.style.left = projectedLatLng.x - Math.floor(offsetWidth / 2) + 'px';
}
function draw() {
var projection = this.getProjection(),
projectedLatLng = projection.fromLatLngToDivPixel(this.point);
positionOverlayByDimensions.call(this, projectedLatLng);
}
function BaseOverlay(options) {
var point = options.point;
this.el = options.el;
this.point = new google.maps.LatLng(point.lat, point.lng);
this.el.style.position = 'absolute';
}
BaseOverlay.prototype = Object.create(google.maps.OverlayView.prototype);
BaseOverlay.prototype.constructor = BaseOverlay;
BaseOverlay.prototype.onAdd = onAdd;
BaseOverlay.prototype.draw = draw;
module.exports = BaseOverlay;
|
Add provider field for future use | <?php
namespace Zeropingheroes\Lanager\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Game extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'provider' => 'steam',
'url' => $this->url(),
'logo' => [
'small' => $this->logo('small'),
'medium' => $this->logo('medium'),
'large' => $this->logo('large'),
],
'links' => [
'self' => route('api.games.show', ['game' => $this->id]),
],
];
}
}
| <?php
namespace Zeropingheroes\Lanager\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Game extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'url' => $this->url(),
'logo' => [
'small' => $this->logo('small'),
'medium' => $this->logo('medium'),
'large' => $this->logo('large'),
],
'links' => [
'self' => route('api.games.show', ['game' => $this->id]),
],
];
}
}
|
Update form binding for migration | /* eslint-disable require-jsdoc,max-len */
import 'whatwg-fetch';
function migrate(username, password) {
const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
return fetch('https://stone.csh.rit.edu/migrate/', {
method: 'POST',
body: formData,
})
.then(() => {
console.log('[MIGRATE] Migration request completed');
})
.catch((error) => {
console.error('[MIGRATE] Migration request failed:', error);
});
}
function inject() {
try {
const loginForm = document.querySelector('form[action*="login-actions/authenticate"');
const submitBtn = loginForm.querySelector('input[type="submit"]');
const usernameField = loginForm.querySelector('input[name="username"]');
const passwordField = loginForm.querySelector('input[name="password"]');
if (usernameField && passwordField) {
submitBtn.addEventListener('click', function() {
submitBtn.disabled = true;
migrate(usernameField.value, passwordField.value)
.then(() => {
loginForm.submit();
});
return false;
});
}
} catch (e) {
console.error('[MIGRATE] Failed to bind to form:', e);
}
}
module.exports = inject;
| /* eslint-disable require-jsdoc,max-len */
import 'whatwg-fetch';
function migrate(username, password) {
const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
return fetch('https://stone.csh.rit.edu/migrate/', {
method: 'POST',
body: formData,
})
.then(() => {
console.log('[MIGRATE] Migration request completed');
})
.catch((error) => {
console.error('[MIGRATE] Migration request failed:', error);
});
}
function inject() {
try {
const loginForm = document.querySelector('form[action*="login-actions/authenticate"');
const submitBtn = loginForm.querySelector('input[type="submit"]');
submitBtn.addEventListener('click', function() {
submitBtn.disabled = true;
const usernameField = loginForm.querySelector('input[name="username"]');
const passwordField = loginForm.querySelector('input[name="password"]');
if (usernameField && passwordField) {
migrate(usernameField.value, passwordField.value)
.then(() => {
loginForm.submit();
});
return false;
}
return true;
});
} catch (e) {
console.error('[MIGRATE] Failed to bind to form:', e);
return true;
}
}
module.exports = inject;
|
Raise StopAsyncIteration instead of StopAsyncIteration in aiter wrapper. | """
Miscellaneous utilities used throughout the library.
"""
import collections.abc
class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator):
"""
Transforms an `__iter__` method into an `__aiter__` method.
"""
def __init__(self, iterator: collections.abc.Iterator):
self._it = iterator
# magic methods
def __iter__(self):
return self
def __next__(self):
return self._it.__next__()
def __aiter__(self):
return self
async def __anext__(self):
try:
return self.__next__()
except StopIteration:
raise StopAsyncIteration
def iter_to_aiter(type_):
"""
Transforms a normal iterable type into an async iterable type.
"""
def __aiter__(self):
return IterToAiter(iter(self))
type_.__aiter__ = __aiter__
return type_
| """
Miscellaneous utilities used throughout the library.
"""
import collections.abc
class IterToAiter(collections.abc.Iterator, collections.abc.AsyncIterator):
"""
Transforms an `__iter__` method into an `__aiter__` method.
"""
def __init__(self, iterator: collections.abc.Iterator):
self._it = iterator
# magic methods
def __iter__(self):
return self
def __next__(self):
return self._it.__next__()
def __aiter__(self):
return self
async def __anext__(self):
return self.__next__()
def iter_to_aiter(type_):
"""
Transforms a normal iterable type into an async iterable type.
"""
def __aiter__(self):
return IterToAiter(iter(self))
type_.__aiter__ = __aiter__
return type_
|
Replace for in loop with forEach. | var detective = require('detective');
var unique = require('array-unique');
var recursive = require('recursive-readdir');
var fs = require('fs');
var core = require('is-core-module');
var local = /^\.|\//;
// Only js and not from node_modules
var onlySourceFiles = function(filename) {
return filename
&& filename.slice(filename.length - 3) === '.js'
&& filename.indexOf('node_modules') === -1;
};
var onlyDependencies = function(filename) {
return !local.test(filename)
&& !core(filename);
};
var find = function(path, cb) {
recursive(path, function (err, filenames) {
var jsFiles = filenames.filter(onlySourceFiles);
var counter = 0;
var requires = [];
jsFiles.forEach(function(filename) {
counter++;
fs.readFile(filename, function(err, content) {
if (err) {
return cb(err, null);
}
counter--;
requires = requires.concat(detective(content));
if (counter === 0) {
cb(null, unique(requires.filter(onlyDependencies)));
}
});
});
});
};
module.exports = find;
| var detective = require('detective');
var unique = require('array-unique');
var recursive = require('recursive-readdir');
var fs = require('fs');
var core = require('is-core-module');
var local = /^\.|\//;
// Only js and not from node_modules
var onlySourceFiles = function(filename) {
return filename
&& filename.slice(filename.length - 3) === '.js'
&& filename.indexOf('node_modules') === -1;
};
var onlyDependencies = function(filename) {
return !local.test(filename)
&& !core(filename);
};
var find = function(path, cb) {
recursive(path, function (err, filenames) {
var jsFiles = filenames.filter(onlySourceFiles);
var counter = 0;
var requires = [];
for (var i in jsFiles) {
counter++;
var filename = jsFiles[i];
fs.readFile(filename, function(err, content) {
if (err) {
return cb(err, null);
}
counter--;
requires = requires.concat(detective(content));
if (counter === 0) {
cb(null, unique(requires.filter(onlyDependencies)));
}
});
}
});
};
module.exports = find;
|
Update presubmit to use 'dart format' command
The presubmit checks will then work with the Flutter SDK in the path.
This is the case when working on the Flutter web app current_results_ui.
Change-Id: I8a8d5db4454b57bc7936197032460e877037b386
Reviewed-on: https://dart-review.googlesource.com/c/dart_ci/+/191921
Reviewed-by: Alexander Thomas <29642742b6693024c89de8232f2e2542cf7eedf7@google.com> | # Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""Presubmit script for dart_ci repository.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into git cl.
"""
import subprocess
def _NeedsFormat(path):
return subprocess.call(['dart', 'format', '--set-exit-if-changed',
'--output','none', path]) != 0
def _CheckDartFormat(input_api, output_api):
files = [
git_file.AbsoluteLocalPath()
for git_file in input_api.AffectedTextFiles()
]
unformatted_files = [
path for path in files
if path.endswith('.dart') and _NeedsFormat(path)
]
if unformatted_files:
escapedNewline = ' \\\n'
return [
output_api.PresubmitError(
'File output does not match dartfmt.\n'
'Fix these issues with:\n'
'dart format%s%s' %
(escapedNewline, escapedNewline.join(unformatted_files)))
]
return []
def CommonChecks(input_api, output_api):
return _CheckDartFormat(input_api, output_api)
CheckChangeOnCommit = CommonChecks
CheckChangeOnUpload = CommonChecks
| # Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""Presubmit script for dart_ci repository.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into git cl.
"""
import subprocess
def _NeedsFormat(path):
return subprocess.call(['dartfmt', '--set-exit-if-changed', '-n', path]) != 0
def _CheckDartFormat(input_api, output_api):
files = [
git_file.AbsoluteLocalPath()
for git_file in input_api.AffectedTextFiles()
]
unformatted_files = [
path for path in files
if path.endswith('.dart') and _NeedsFormat(path)
]
if unformatted_files:
escapedNewline = ' \\\n'
return [
output_api.PresubmitError(
'File output does not match dartfmt.\n'
'Fix these issues with:\n'
'dartfmt -w%s%s' %
(escapedNewline, escapedNewline.join(unformatted_files)))
]
return []
def CommonChecks(input_api, output_api):
return _CheckDartFormat(input_api, output_api)
CheckChangeOnCommit = CommonChecks
CheckChangeOnUpload = CommonChecks
|
Use post value from config | import os
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.httpserver import HTTPServer
from . import handlers
from .conf import config
class LogsterApplication(Application):
handlers = [
(r'/', handlers.IndexHandler),
]
settings = {
'template_path': os.path.join(
os.path.dirname(__file__), '../templates')
}
def __init__(self):
super(LogsterApplication, self).__init__(
handlers=self.handlers,
**self.settings
)
def run_server():
app = LogsterApplication()
server = HTTPServer(app)
server.listen(config['app']['port'])
IOLoop.current().start()
| import os
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.httpserver import HTTPServer
from . import handlers
class LogsterApplication(Application):
handlers = [
(r'/', handlers.IndexHandler),
]
settings = {
'template_path': os.path.join(
os.path.dirname(__file__), '../templates')
}
def __init__(self):
super(LogsterApplication, self).__init__(
handlers=self.handlers,
**self.settings
)
def run_server():
app = LogsterApplication()
server = HTTPServer(app)
server.listen(8888)
IOLoop.current().start()
|
Fix from number on Load testing client | import logging
from flask import current_app
from app.clients.sms.firetext import (
FiretextClient
)
logger = logging.getLogger(__name__)
class LoadtestingClient(FiretextClient):
'''
Loadtest sms client.
'''
def init_app(self, config, statsd_client, *args, **kwargs):
super(FiretextClient, self).__init__(*args, **kwargs)
self.current_app = current_app
self.api_key = config.config.get('LOADTESTING_API_KEY')
self.from_number = config.config.get('FROM_NUMBER')
self.name = 'loadtesting'
self.url = "https://www.firetext.co.uk/api/sendsms/json"
self.statsd_client = statsd_client
| import logging
from flask import current_app
from app.clients.sms.firetext import (
FiretextClient
)
logger = logging.getLogger(__name__)
class LoadtestingClient(FiretextClient):
'''
Loadtest sms client.
'''
def init_app(self, config, statsd_client, *args, **kwargs):
super(FiretextClient, self).__init__(*args, **kwargs)
self.current_app = current_app
self.api_key = config.config.get('LOADTESTING_API_KEY')
self.from_number = config.config.get('LOADTESTING_NUMBER')
self.name = 'loadtesting'
self.url = "https://www.firetext.co.uk/api/sendsms/json"
self.statsd_client = statsd_client
|
Reorder object definition for error data | var LogEmitter = function (source) {
this.source = source;
};
LogEmitter.prototype.info = function (message) {
process.emit("gulp:log", { level: "info", message: message, source: this.source });
};
LogEmitter.prototype.warn = function (message) {
process.emit("gulp:log", { level: "warn", message: message, source: this.source });
};
LogEmitter.prototype.error = function (message) {
var data = {
level: "error",
message: message,
source: this.source
};
if (message instanceof Error) {
data.message = message.message;
data.error = message;
}
process.emit("gulp:log", data);
};
LogEmitter.prototype.debug = function (message) {
process.emit("gulp:log", { level: "debug", message: message, source: this.source });
};
module.exports = {
Logger: function (source) {
return new LogEmitter(source);
}
};
// var log = require('gulp-logemitter').Logger('my plugin');
// log.info("This is something to say"); | var LogEmitter = function (source) {
this.source = source;
};
LogEmitter.prototype.info = function (message) {
process.emit("gulp:log", { level: "info", message: message, source: this.source });
};
LogEmitter.prototype.warn = function (message) {
process.emit("gulp:log", { level: "warn", message: message, source: this.source });
};
LogEmitter.prototype.error = function (message) {
var data = {};
data.level = "error";
data.message = message;
data.source = this.source;
if (message instanceof Error) {
data.message = message.message;
data.error = message;
}
process.emit("gulp:log", data);
};
LogEmitter.prototype.debug = function (message) {
process.emit("gulp:log", { level: "debug", message: message, source: this.source });
};
module.exports = {
Logger: function (source) {
return new LogEmitter(source);
}
};
// var log = require('gulp-logemitter').Logger('my plugin');
// log.info("This is something to say"); |
Fix leftover artifact from refactor | 'use strict';
var exec = require('child_process').exec;
var serialNumber = function (cb, cmdPrefix) {
var delimiter = ': ';
var stdoutHandler = function (error, stdout) {
cb(error, parseResult(stdout));
};
var parseResult = function (input) {
return input.slice(input.indexOf(delimiter) + 2).trim();
};
if (!cmdPrefix) {cmdPrefix = '';}
switch (process.platform) {
case 'darwin':
exec(cmdPrefix + 'system_profiler SPHardwareDataType | grep \'Serial\'', stdoutHandler);
break;
case 'win32':
delimiter = '\r\n';
exec('wmic csproduct get identifyingnumber', stdoutHandler);
break;
case 'linux':
case 'freebsd':
exec(cmdPrefix + 'dmidecode -t system | grep \'Serial\'', function (error, stdout) {
if (error || parseResult(stdout).length > 1) {
stdoutHandler(error, stdout);
} else {
exec(cmdPrefix + 'dmidecode -t system | grep \'UUID\'', stdoutHandler);
}
});
break;
}
};
module.exports = exports = serialNumber;
exports.useSudo = function (cb) {
serialNumber(cb, 'sudo ');
};
| 'use strict';
var exec = require('child_process').exec;
var serialNumber = function (cb, cmdPrefix) {
var delimiter = ': ';
var stdoutHandler = function (error, stdout) {
cb(error, parseResult(stdout));
};
var parseResult = function (input) {
return input.slice(input.indexOf(delimiter) + 2).trim();
};
if (!cmdPrefix) {cmdPrefix = '';}
switch (process.platform) {
case 'darwin':
exec(cmdPrefix + 'system_profiler SPHardwareDataType | grep \'Serial\'', stdoutHandler);
break;
case 'win32':
delimiter = '\r\n';
exec('wmic csproduct get identifyingnumber', stdoutHandler);
break;
case 'linux':
case 'freebsd':
exec(cmdPrefix + 'dmidecode -t system | grep \'Serial\'', function (error, stdout) {
if (error || parseResult(stdout).length > 1) {
stdoutHandler(error, stdout);
} else {
exec(this.cmdPrefix + 'dmidecode -t system | grep \'UUID\'', stdoutHandler);
}
});
break;
}
};
module.exports = exports = serialNumber;
exports.useSudo = function (cb) {
serialNumber(cb, 'sudo ');
};
|
Fix nearby stops not loading | import { observable, action, reaction } from 'mobx';
import storeCoords from 'stores/coords.js';
export default new class StoreSearch {
dispose = 0
@observable
query = ''
@observable
type = 'stops'
@observable.struct
results = {
stops: [],
routes: []
}
// Start fetching nearby search results on location update.
startScanning() {
this.dispose = reaction(() => ({
lat: storeCoords.lat,
lng: storeCoords.lng
}), () => {
if (!this.query) this.fetchResults();
}, { fireImmediately: true });
}
// Stop fetching nearby search results on location update.
stopScanning() {
this.dispose();
}
@action
updateQuery(query) {
this.query = query;
}
@action
updateType(type) {
this.type = type;
}
@action.bound
async fetchResults() {
const [ query, lat, lng ] = [ this.query, storeCoords.lat, storeCoords.lng ];
// Return on manual search or if coordinates unavailable.
if (query || !lat || !lng) return;
// Fetch search results.
const results = await (await fetch(`${process.env['REACT_APP_API']}/search?${query ? `&query=${query}` : ''}${lat && lng ? `&lat=${lat}&lng=${lng}` : ''}`)).json();
if (results) this.results = results;
}
};
| import { observable, action, reaction } from 'mobx';
import storeCoords from 'stores/coords.js';
export default new class StoreSearch {
dispose = 0
@observable
query = ''
@observable
type = 'stops'
@observable.struct
results = {
stops: [],
routes: []
}
startScanning() {
this.dispose = reaction(() => ({
lat: storeCoords.lat,
lng: storeCoords.lng
}), () => {
if (!this.query) this.fetchResults();
});
}
stopScanning() {
this.dispose();
}
@action
updateQuery(query) {
this.query = query;
}
@action
updateType(type) {
this.type = type;
}
@action.bound
async fetchResults() {
const [ query, lat, lng ] = [ this.query, storeCoords.lat, storeCoords.lng ];
const results = query || (lat && lng) ? await (await fetch(`${process.env['REACT_APP_API']}/search?${query ? `&query=${query}` : ''}${lat && lng ? `&lat=${lat}&lng=${lng}` : ''}`)).json() : {};
this.results = results;
}
};
|
Fix missing colon in video url | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.urls import path
# Views
from . import views
# Application namespace
app_name = 'video'
urlpatterns = [
path('<int:videoid>/', views.video_view, name='glossvideo'),
path('poster/<int:videoid>', views.poster_view, name='glossvideo_poster'),
path('upload/', views.upload_glossvideo_view, name='upload_glossvideo'),
path('upload/gloss/', views.upload_glossvideo_gloss_view, name='upload_glossvideo_gloss'),
path('upload/recorded/', views.add_recorded_video_view, name='add_recorded_video'),
# View to upload multiple videos with no foreign key to gloss.
path('add/', views.addvideos_formview, name='upload_videos'),
# View that shows a list of glossvideos with no foreign key to gloss, user can add fk to gloss for glossvideos.
path('uploaded/', views.uploaded_glossvideos_listview, name='manage_videos'),
# View that updates a glossvideo
path('update/', views.update_glossvideo_view, name='glossvideo_update'),
# View that handles the upload of poster file
path('add/poster', views.add_poster_view, name='add_poster'),
# Change priority of video
path('order/', views.change_glossvideo_order, name='change_glossvideo_order'),
# Change publicity of video
path('publicity/', views.change_glossvideo_publicity, name='change_glossvideo_publicity'),
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.urls import path
# Views
from . import views
# Application namespace
app_name = 'video'
urlpatterns = [
path('<intvideoid>/', views.video_view, name='glossvideo'),
path('poster/<int:videoid>', views.poster_view, name='glossvideo_poster'),
path('upload/', views.upload_glossvideo_view, name='upload_glossvideo'),
path('upload/gloss/', views.upload_glossvideo_gloss_view, name='upload_glossvideo_gloss'),
path('upload/recorded/', views.add_recorded_video_view, name='add_recorded_video'),
# View to upload multiple videos with no foreign key to gloss.
path('add/', views.addvideos_formview, name='upload_videos'),
# View that shows a list of glossvideos with no foreign key to gloss, user can add fk to gloss for glossvideos.
path('uploaded/', views.uploaded_glossvideos_listview, name='manage_videos'),
# View that updates a glossvideo
path('update/', views.update_glossvideo_view, name='glossvideo_update'),
# View that handles the upload of poster file
path('add/poster', views.add_poster_view, name='add_poster'),
# Change priority of video
path('order/', views.change_glossvideo_order, name='change_glossvideo_order'),
# Change publicity of video
path('publicity/', views.change_glossvideo_publicity, name='change_glossvideo_publicity'),
]
|
Exclude dark-colored theme from stylesheet gallery. | # -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles
def simple_plot(stylename):
"""Generate a simple plot using a given matplotlib style."""
if stylename == 'typhon-dark':
# TODO: Sphinx build is broken for non-white figure facecolor.
return
x = np.linspace(0, np.pi, 20)
fig, ax = plt.subplots()
for s in np.linspace(0, np.pi / 2, 12):
ax.plot(x, np.sin(x+s),
label=r'$\Delta\omega = {:.2f}$'.format(s),
marker='.',
)
ax.set_ylabel('y-axis')
ax.set_xlabel('x-axis')
ax.set_title(stylename)
ax.grid()
ax.legend()
# Create plot using default styles.
simple_plot('matplotlib 2.0')
# Create a plot for each available typhon style.
for style_name in styles.available:
with plt.style.context(styles(style_name)):
simple_plot(style_name)
plt.show()
| # -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles
def simple_plot(stylename):
"""Generate a simple plot using a given matplotlib style."""
x = np.linspace(0, np.pi, 20)
fig, ax = plt.subplots()
for s in np.linspace(0, np.pi / 2, 12):
ax.plot(x, np.sin(x+s),
label=r'$\Delta\omega = {:.2f}$'.format(s),
marker='.',
)
ax.set_ylabel('y-axis')
ax.set_xlabel('x-axis')
ax.set_title(stylename)
ax.grid()
ax.legend()
# Create plot using default styles.
simple_plot('matplotlib 2.0')
# Create a plot for each available typhon style.
for style_name in styles.available:
with plt.style.context(styles(style_name)):
simple_plot(style_name)
plt.show()
|
Append a trailing newline to the project directory | """
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 os.path
from django import forms
from preferences.models import Preference
class PreferencesForm(forms.Form):
def __init__(self, *args, **kwargs):
super(PreferencesForm, self).__init__(*args, **kwargs)
for preference in Preference.objects.all():
self.fields[preference.name] = forms.CharField()
def clean(self):
# Apparently clean__projects_directory doesn't work with dynamic forms
if not self.cleaned_data['projects_directory'].endswith(os.path.sep):
self.cleaned_data['projects_directory'] += os.path.sep
return self.cleaned_data
| """
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from django import forms
from preferences.models import Preference
class PreferencesForm(forms.Form):
def __init__(self, *args, **kwargs):
super(PreferencesForm, self).__init__(*args, **kwargs)
for preference in Preference.objects.all():
self.fields[preference.name] = forms.CharField()
|
Make sure seeder creates random values | """
Contains factory classes for quickly generating test data.
It uses the factory_boy package.
Please see https://github.com/rbarrois/factory_boy for more info
"""
import datetime
import factory
import factory.fuzzy
import random
from django.utils import timezone
from ratings import models
class SubmissionFactory(factory.DjangoModelFactory):
class Meta:
model = models.Submission
application_date = factory.fuzzy.FuzzyDateTime(timezone.now(), timezone.now() + datetime.timedelta(days=30))
submission_date = factory.fuzzy.FuzzyDateTime(timezone.now(), timezone.now() + datetime.timedelta(days=100))
class MediaFactory(factory.DjangoModelFactory):
class Meta:
model = models.Media
filename = factory.Faker('file_name')
filetype = factory.Faker('pystr', max_chars=60)
submission = factory.SubFactory(SubmissionFactory)
class RatingFactory(factory.DjangoModelFactory):
class Meta:
model = models.Rating
score = factory.Faker('pydecimal', left_digits=2, right_digits=1, positive=True)
code_quality = factory.fuzzy.FuzzyInteger(0,100)
documentation = factory.fuzzy.FuzzyInteger(0,100)
problem_solving = factory.fuzzy.FuzzyInteger(0,100)
effort = factory.fuzzy.FuzzyInteger(0,100)
creativity = factory.fuzzy.FuzzyInteger(0,100)
originality = factory.fuzzy.FuzzyInteger(0,100)
submission = factory.SubFactory(SubmissionFactory)
| """
Contains factory classes for quickly generating test data.
It uses the factory_boy package.
Please see https://github.com/rbarrois/factory_boy for more info
"""
import datetime
import factory
import random
from django.utils import timezone
from ratings import models
class SubmissionFactory(factory.DjangoModelFactory):
class Meta:
model = models.Submission
application_date = timezone.now() - datetime.timedelta(days=random.randint(0, 5))
submission_date = timezone.now() + datetime.timedelta(days=random.randint(1, 5))
class MediaFactory(factory.DjangoModelFactory):
class Meta:
model = models.Media
filename = factory.Faker('file_name')
filetype = factory.Faker('pystr', max_chars=60)
submission = factory.SubFactory(SubmissionFactory)
class RatingFactory(factory.DjangoModelFactory):
class Meta:
model = models.Rating
score = factory.Faker('pydecimal', left_digits=2, right_digits=1, positive=True)
code_quality = random.randint(0,100)
documentation = random.randint(0,100)
problem_solving = random.randint(0,100)
effort = random.randint(0,100)
creativity = random.randint(0,100)
originality = random.randint(0,100)
submission = factory.SubFactory(SubmissionFactory)
|
Implement relative path (use loadname) for Templates | def linebreak_iter(template_source):
yield 0
p = template_source.find('\n')
while p >= 0:
yield p + 1
p = template_source.find('\n', p + 1)
yield len(template_source) + 1
def get_data_from_template(source):
origin, (start, end) = source
template_source = origin.reload()
lineno = None
upto = 0
source_lines = []
for num, next in enumerate(linebreak_iter(template_source)):
if start >= upto and end <= next:
lineno = num
source_lines.append(template_source[upto:next])
upto = next
if not source_lines or lineno is None:
return {}
pre_context = source_lines[max(lineno - 3, 0):lineno]
post_context = source_lines[(lineno + 1):(lineno + 4)]
context_line = source_lines[lineno]
return {
'sentry.interfaces.Template': {
'filename': origin.loadname,
'abs_path': origin.name,
'pre_context': pre_context,
'context_line': context_line,
'lineno': lineno,
'post_context': post_context,
},
'culprit': origin.loadname,
}
| def linebreak_iter(template_source):
yield 0
p = template_source.find('\n')
while p >= 0:
yield p + 1
p = template_source.find('\n', p + 1)
yield len(template_source) + 1
def get_data_from_template(source):
origin, (start, end) = source
template_source = origin.reload()
lineno = None
upto = 0
source_lines = []
for num, next in enumerate(linebreak_iter(template_source)):
if start >= upto and end <= next:
lineno = num
source_lines.append(template_source[upto:next])
upto = next
if not source_lines or lineno is None:
return {}
pre_context = source_lines[max(lineno - 3, 0):lineno]
post_context = source_lines[(lineno + 1):(lineno + 4)]
context_line = source_lines[lineno]
return {
'sentry.interfaces.Template': {
'filename': origin.name,
'pre_context': pre_context,
'context_line': context_line,
'lineno': lineno,
'post_context': post_context,
},
'culprit': origin.loadname,
}
|
Add new constans for auth-card actions and shop actions | // auth constants
export const AUTH_USER = 'AUTH_USER';
export const UNAUTH_USER = 'UNAUTH_USER';
export const AUTH_ERROR = 'AUTH_ERROR';
export const SET_USER_DATA = 'SET_USER_DATA';
export const SET_CREDIT_CARDS = 'SET_CREDIT_CARDS';
export const SET_DEFAULT_CARD = 'SET_DEFAULT_CARD';
export const ADD_CREDIT_CARD = 'ADD_CREDIT_CARD';
// products constants
export const SELECT_PRODUCT = 'SELECT_PRODUCT';
export const SET_PRODUCTS = 'SET_PRODUCTS';
export const UPDATE_PRODUCT = 'UPDATE_PRODUCT';
export const LOADING = 'LOADING';
export const LOADING_PER_PAGE = 'LOADING_PER_PAGE';
export const SET_PAGES_PRODUCTS = 'SET_PAGES_PRODUCTS';
export const ADD_PRODUCTS_COLLECTION = 'ADD_PRODUCTS_COLLECTION';
export const SET_PAGES_SHOWING = 'SET_PAGES_SHOWING';
export const ERROR_TO_GET_PRODUCT = 'ERROR_TO_GET_PRODUCT';
// categories constants
export const SET_CATEGORIES = 'SET_CATEGORIES';
export const SELECT_CATEGORY = 'SELECT_CATEGORY';
// Shop constants
export const SET_TOKEN_CARD = 'SET_TOKEN_CARD';
export const SELECT_CARD = 'SELECT_CARD';
export const ADD_PRODUCT_TO_CAR = 'ADD_PRODUCT_TO_CAR' | // auth constants
export const AUTH_USER = 'AUTH_USER';
export const UNAUTH_USER = 'UNAUTH_USER';
export const AUTH_ERROR = 'AUTH_ERROR';
export const SET_USER_DATA = 'SET_USER_DATA';
export const SET_CREDIT_CARDS = 'SET_CREDIT_CARDS';
export const SET_DEFAULT_CARD = 'SET_DEFAULT_CARD';
// products constants
export const SELECT_PRODUCT = 'SELECT_PRODUCT';
export const SET_PRODUCTS = 'SET_PRODUCTS';
export const UPDATE_PRODUCT = 'UPDATE_PRODUCT';
export const LOADING = 'LOADING';
export const LOADING_PER_PAGE = 'LOADING_PER_PAGE';
export const SET_PAGES_PRODUCTS = 'SET_PAGES_PRODUCTS';
export const ADD_PRODUCTS_COLLECTION = 'ADD_PRODUCTS_COLLECTION';
export const SET_PAGES_SHOWING = 'SET_PAGES_SHOWING';
export const ERROR_TO_GET_PRODUCT = 'ERROR_TO_GET_PRODUCT';
// categories constants
export const SET_CATEGORIES = 'SET_CATEGORIES';
export const SELECT_CATEGORY = 'SELECT_CATEGORY';
// Shop constants
export const SET_TOKEN_CARD = 'SET_TOKEN_CARD';
export const SELECT_CARD = 'SELECT_CARD';
export const ADD_PRODUCT_TO_CAR = 'ADD_PRODUCT_TO_CAR' |
Remove unrequired test for validating removed method withRequest | <?php
/*
* Copyright (c) 2016 Refinery29, Inc.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace spec\Refinery29\Piston\Middleware;
use PhpSpec\ObjectBehavior;
use Refinery29\Piston\ApiResponse;
use Refinery29\Piston\Middleware\HasMiddleware;
use Refinery29\Piston\Middleware\Payload;
use Refinery29\Piston\Request;
/**
* @mixin Payload
*/
class PayloadSpec extends ObjectBehavior
{
public function let(HasMiddleware $subject, Request $request, ApiResponse $response)
{
$this->beConstructedWith($subject, $request, $response);
}
public function it_is_initializable()
{
$this->shouldHaveType(Payload::class);
}
public function it_can_get_subject()
{
$this->getSubject()->shouldHaveType(HasMiddleware::class);
}
public function it_can_get_request()
{
$this->getRequest()->shouldHaveType(Request::class);
}
public function it_can_get_response()
{
$this->getResponse()->shouldHaveType(ApiResponse::class);
}
}
| <?php
/*
* Copyright (c) 2016 Refinery29, Inc.
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace spec\Refinery29\Piston\Middleware;
use PhpSpec\ObjectBehavior;
use Refinery29\Piston\ApiResponse;
use Refinery29\Piston\Middleware\HasMiddleware;
use Refinery29\Piston\Middleware\Payload;
use Refinery29\Piston\Request;
/**
* @mixin Payload
*/
class PayloadSpec extends ObjectBehavior
{
public function let(HasMiddleware $subject, Request $request, ApiResponse $response)
{
$this->beConstructedWith($subject, $request, $response);
}
public function it_is_initializable()
{
$this->shouldHaveType(Payload::class);
}
public function it_can_get_subject()
{
$this->getSubject()->shouldHaveType(HasMiddleware::class);
}
public function it_can_get_request()
{
$this->getRequest()->shouldHaveType(Request::class);
}
public function it_can_get_response()
{
$this->getResponse()->shouldHaveType(ApiResponse::class);
}
public function it_can_set_request_immutably()
{
$request = new Request();
$payload = $this->withRequest($request);
$payload->shouldHaveType(Payload::class);
$payload->getRequest()->shouldEqual($request);
}
}
|
Add greeting when logged into the account | // Copyright 2019 Google LLC
//
// 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
//
// https://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.
function retrieveAccountInfo() {
fetch("/account").then(response => {
if (response.redirected) return;
else return response.json();
}).then(account => {
// Filling out the form with the account information.
document.getElementById("logout").href = account.logoutUrl;
if (account.isUserBusinessOwner) {
document.getElementById("businessName").value = account.nickname;
} else {
document.getElementById("nickname").value = account.nickname;
}
document.getElementById("street").value = account.street;
document.getElementById("city").value = account.city;
document.getElementById("state").value = account.state;
document.getElementById("zipCode").value = account.zipCode;
document.getElementById("userGreeting").innerText = "Hello, " + account.nickname;
});
}
| // Copyright 2019 Google LLC
//
// 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
//
// https://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.
function retrieveAccountInfo() {
fetch("/account").then(response => {
if (response.redirected) return;
else return response.json();
}).then(account => {
// Filling out the form with the account information.
document.getElementById("logout").href = account.logoutUrl;
if (account.isUserBusinessOwner) {
document.getElementById("businessName").value = account.nickname;
} else {
document.getElementById("nickname").value = account.nickname;
}
document.getElementById("street").value = account.street;
document.getElementById("city").value = account.city;
document.getElementById("state").value = account.state;
document.getElementById("zipCode").value = account.zipCode;
document.getElementById("userGreeting").value = account.nickname;
});
}
|
TST: Use python3 for test_docstring_optimization_compat subprocess | import subprocess
import pytest
from statsmodels.compat.platform import PLATFORM_WIN
from statsmodels.compat.scipy import SCIPY_11
def test_lazy_imports():
# Check that when statsmodels.api is imported, matplotlib is _not_ imported
cmd = ("import statsmodels.api as sm; "
"import sys; "
"mods = [x for x in sys.modules if 'matplotlib.pyplot' in x]; "
"assert not mods, mods")
# TODO: is there a cleaner way to do this import in an isolated environment
pyexe = 'python3' if not PLATFORM_WIN else 'python'
p = subprocess.Popen(pyexe + ' -c "' + cmd + '"',
shell=True, close_fds=True)
p.wait()
rc = p.returncode
assert rc == 0
@pytest.mark.skipif(SCIPY_11, reason='SciPy raises on -OO')
def test_docstring_optimization_compat():
# GH#5235 check that importing with stripped docstrings doesn't raise
pyexe = 'python3' if not PLATFORM_WIN else 'python'
p = subprocess.Popen(pyexe + ' -OO -c "import statsmodels.api as sm"',
shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.communicate()
rc = p.returncode
assert rc == 0, out
| import subprocess
import pytest
from statsmodels.compat.platform import PLATFORM_WIN
from statsmodels.compat.scipy import SCIPY_11
def test_lazy_imports():
# Check that when statsmodels.api is imported, matplotlib is _not_ imported
cmd = ("import statsmodels.api as sm; "
"import sys; "
"mods = [x for x in sys.modules if 'matplotlib.pyplot' in x]; "
"assert not mods, mods")
# TODO: is there a cleaner way to do this import in an isolated environment
pyexe = 'python3' if not PLATFORM_WIN else 'python'
p = subprocess.Popen(pyexe + ' -c "' + cmd + '"',
shell=True, close_fds=True)
p.wait()
rc = p.returncode
assert rc == 0
@pytest.mark.skipif(SCIPY_11, reason='SciPy raises on -OO')
def test_docstring_optimization_compat():
# GH#5235 check that importing with stripped docstrings doesn't raise
p = subprocess.Popen('python -OO -c "import statsmodels.api as sm"',
shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.communicate()
rc = p.returncode
assert rc == 0, out
|
Add position table and add field mid in box tables | from django.db import models
# Create your models here.
class User(models.Model):
uid = models.AutoField(primary_key=True)
uname = models.CharField(max_length=128)
session = models.CharField(max_length=35,unique=True)
class Box(models.Model):
bid = models.AutoField(primary_key=True)
level = models.IntegerField()
mid = models.ForeignKey("Monster")
owner = models.ForeignKey("User")
class Party(models.Model):
uid = models.ForeignKey("User")
fir = models.ForeignKey("Box",related_name="first")
sec = models.ForeignKey("Box",related_name="second")
thi = models.ForeignKey("Box",related_name="third")
fou = models.ForeignKey("Box",related_name="fourth")
class Position(models.Model):
uid = models.ForeignKey("User")
latitude = models.FloatField()
longitude = models.FloatField()
time = models.DateField(auto_now=True)
class Monster(models.Model):
mid = models.AutoField(primary_key=True)
mname = models.CharField(max_length=128)
initHP = models.IntegerField()
initAtk = models.IntegerField()
groHP = models.FloatField()
groAtk = models.FloatField()
class Skill(models.Model):
sid = models.AutoField(primary_key=True)
target = models.CharField(max_length=40)
function = models.TextField()
| from django.db import models
# Create your models here.
class User(models.Model):
uid = models.AutoField(primary_key=True)
uname = models.CharField(max_length=128)
session = models.CharField(max_length=35,unique=True)
class Box(models.Model):
bid = models.AutoField(primary_key=True)
level = models.IntegerField()
owner = models.ForeignKey("User")
class Party(models.Model):
uid = models.ForeignKey("User")
fir = models.ForeignKey("Box",related_name="first")
sec = models.ForeignKey("Box",related_name="second")
thi = models.ForeignKey("Box",related_name="third")
fou = models.ForeignKey("Box",related_name="fourth")
class Monster(models.Model):
mid = models.AutoField(primary_key=True)
mname = models.CharField(max_length=128)
initHP = models.IntegerField()
initAtk = models.IntegerField()
groHP = models.FloatField()
groAtk = models.FloatField()
class Skill(models.Model):
sid = models.AutoField(primary_key=True)
target = models.CharField(max_length=40)
function = models.TextField()
|
Add support for Redis cloud | import kue from 'kue';
import { isNil } from 'ramda';
const queue = kue.createQueue({
redis: process.env.REDISCLOUD_URL || 'redis://127.0.0.1:6379',
});
export const publishTaker = (payload) => {
console.info(`Publishing:`);
console.info(payload);
return queue.create('taker', {
title: 'Taker',
payload,
})
.priority('high')
// @TODO for when client connections die?
// For now we can restart jobs from the UI
// .ttl(1000000)
// .attempts(3)
.save();
};
export const consumeTaker = (cb) => {
console.info('Consuming...');
queue.process('taker', (job, done) => {
console.info(`Working on:`);
console.info(job.id, job.data);
if (isNil(job)) {
done(new Error('Job was nil'));
cb(new Error('Job was nil'));
}
cb({ job, done });
});
};
export const getActiveTakers = (jobType) =>
new Promise((resolve, reject) => {
kue.Job.rangeByType(jobType, 'active', 0, 9, 'asc', (err, jobs) => {
if (err) {
reject(err);
}
else {
resolve(jobs);
}
});
});
| import kue from 'kue';
import { isNil } from 'ramda';
const queue = kue.createQueue();
export const publishTaker = (payload) => {
console.info(`Publishing:`);
console.info(payload);
return queue.create('taker', {
title: 'Taker',
payload,
})
.priority('high')
// @TODO for when client connections die?
// For now we can restart jobs from the UI
// .ttl(1000000)
// .attempts(3)
.save();
};
export const consumeTaker = (cb) => {
console.info('Consuming...');
queue.process('taker', (job, done) => {
console.info(`Working on:`);
console.info(job.id, job.data);
if (isNil(job)) {
done(new Error('Job was nil'));
cb(new Error('Job was nil'));
}
cb({ job, done });
});
};
export const getActiveTakers = (jobType) =>
new Promise((resolve, reject) => {
kue.Job.rangeByType(jobType, 'active', 0, 9, 'asc', (err, jobs) => {
if (err) {
reject(err);
}
else {
resolve(jobs);
}
});
});
|
GenerateSiteMap.php: Fix broken path to place the sitemap. | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapGenerator;
class GenerateSitemap extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'sitemap:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate the sitemap.';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
SitemapGenerator::create(config('app.url'))
->writeToFile($this->laravel->make('path.public').'/sitemap.xml');
}
}
| <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapGenerator;
class GenerateSitemap extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'sitemap:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate the sitemap.';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
SitemapGenerator::create(config('app.url'))
->writeToFile($this->laravel->make('path.public').'sitemap.xml');
}
}
|
Copy files directly into release/google-site-kit. | /**
* External dependencies
*/
import gulp from 'gulp';
gulp.task( 'copy', () => {
gulp.src(
[
'readme.txt',
'google-site-kit.php',
'uninstall.php',
'dist/*.js',
'dist/assets/**/*',
'bin/**/*',
'includes/**/*',
'third-party/**/*',
'!third-party/**/**/{tests,Tests,doc?(s),examples}/**/*',
'!third-party/**/**/{*.md,*.yml,phpunit.*}',
'!**/*.map',
'!bin/local-env/**/*',
'!bin/local-env/',
'!dist/admin.js',
'!dist/adminbar.js',
'!dist/wpdashboard.js',
],
{ base: '.' }
)
.pipe( gulp.dest( 'release/google-site-kit' ) );
} );
| /**
* External dependencies
*/
import gulp from 'gulp';
gulp.task( 'copy', () => {
gulp.src(
[
'readme.txt',
'google-site-kit.php',
'uninstall.php',
'dist/*.js',
'dist/assets/**/*',
'bin/**/*',
'includes/**/*',
'third-party/**/*',
'!third-party/**/**/{tests,Tests,doc?(s),examples}/**/*',
'!third-party/**/**/{*.md,*.yml,phpunit.*}',
'!**/*.map',
'!bin/local-env/**/*',
'!bin/local-env/',
'!dist/admin.js',
'!dist/adminbar.js',
'!dist/wpdashboard.js',
],
{ base: '.' }
)
.pipe( gulp.dest( 'release' ) );
} );
|
Fix bug in popstate navigating. |
var runway = require('./runway.js')
module.exports = runway
document.onclick = function(event) {
event = event || window.event // IE specials
var target = event.target || event.srcElement // IE specials
if (target.tagName === 'A') {
event.preventDefault()
processLink.call(target)
}
}
function processLink(){
var href = this.href.replace(location.origin,'')
// console.log('processLink', this.href, href)
if (this.dataset.ajax !== 'none') {
goForward(href)
doRoute(href)
return false
}
return true
}
function doRoute(href){
var ctrl = runway.finder(href)
if (ctrl) ctrl()
}
function goForward(url){
var title = Math.random().toString().split('.')[1]
if (history.pushState) history.pushState({url:url, title:title}, null, url)
else location.assign(url)
}
window.addEventListener('popstate',function(event){
doRoute(event.state.url)
})
window.onpopstate = function(event){
// doRoute(event.state.url)
// console.log( event )
// window.alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state))
}
function init(){
history.replaceState( {url:location.pathname}, null, location.pathname )
var ctrl = runway.finder(location.pathname)
if (ctrl) ctrl()
}
// setTimeout(init,100)
window.addEventListener ? addEventListener('load', init, false) : window.attachEvent ? attachEvent('onload', init) : (onload = init)
|
var runway = require('./runway.js')
module.exports = runway
document.onclick = function(event) {
event = event || window.event // IE specials
var target = event.target || event.srcElement // IE specials
if (target.tagName === 'A') {
event.preventDefault()
processLink.call(target)
}
}
function processLink(){
var href = this.href.replace(location.origin,'')
// console.log('processLink', this.href, href)
if (this.dataset.ajax !== 'none') {
goto(href)
return false
}
return true
}
function goto(href){
var ctrl = runway.finder(href)
if (ctrl) {
ctrl()
updateUrl(href)
}
}
function updateUrl(url){
if (history.pushState) history.pushState(null, '', url)
else location.assign(url)
}
window.onpopstate = function(event){
window.alert('location: ' + document.location + ', state: ' + JSON.stringify(event.state))
}
function init(){ goto(location.pathname) }
// setTimeout(init,100)
window.addEventListener ? addEventListener('load', init, false) : window.attachEvent ? attachEvent('onload', init) : (onload = init)
|
Add noop to migration file | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-08 19:56
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations
from corehq.sql_db.operations import HqRunPython
def noop(*args, **kwargs):
pass
def _convert_emailed_to_array_field(apps, schema_editor):
BillingRecord = apps.get_model('accounting', 'BillingRecord')
for record in BillingRecord.objects.all():
if record.emailed_to != '':
record.emailed_to_list = record.emailed_to.split(',')
WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord')
for wirerecord in WireBillingRecord.objects.all():
if wirerecord.emailed_to != '':
wirerecord.emailed_to_list = wirerecord.emailed_to.split(',')
class Migration(migrations.Migration):
dependencies = [
('accounting', '0025_auto_20180508_1952'),
]
operations = [
HqRunPython(_convert_emailed_to_array_field, reverse_code=noop)
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-08 19:56
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations
from corehq.sql_db.operations import HqRunPython
def _convert_emailed_to_array_field(apps, schema_editor):
BillingRecord = apps.get_model('accounting', 'BillingRecord')
for record in BillingRecord.objects.all():
if record.emailed_to != '':
record.emailed_to_list = record.emailed_to.split(',')
WireBillingRecord = apps.get_model('accounting', 'WireBillingRecord')
for wirerecord in WireBillingRecord.objects.all():
if wirerecord.emailed_to != '':
wirerecord.emailed_to_list = wirerecord.emailed_to.split(',')
class Migration(migrations.Migration):
dependencies = [
('accounting', '0025_auto_20180508_1952'),
]
operations = [
HqRunPython(_convert_emailed_to_array_field)
]
|
Fix historyIndex to actually get the last command on key-up | var fs = require('fs');
module.exports = function (repl, file) {
try {
var stat = fs.statSync(file);
repl.rli.history = fs.readFileSync(file, 'utf-8').split('\n').reverse();
repl.rli.history.shift();
repl.rli.historyIndex = -1; // will be incremented before pop
} catch (e) {}
var fd = fs.openSync(file, 'a'), reval = repl.eval;
repl.rli.addListener('line', function(code) {
if (code && code !== '.history') {
fs.write(fd, code + '\n');
} else {
repl.rli.historyIndex++;
repl.rli.history.pop();
}
});
process.on('exit', function() {
fs.closeSync(fd);
});
repl.commands['.history'] = {
help : 'Show the history',
action : function() {
var out = [];
repl.rli.history.forEach(function(v, k) {
out.push(v);
});
repl.outputStream.write(out.reverse().join('\n') + '\n');
repl.displayPrompt();
}
};
};
| var fs = require('fs');
module.exports = function (repl, file) {
try {
var stat = fs.statSync(file);
repl.rli.history = fs.readFileSync(file, 'utf-8').split('\n').reverse();
repl.rli.history.shift();
repl.rli.historyIndex = 0;
} catch (e) {}
var fd = fs.openSync(file, 'a'), reval = repl.eval;
repl.rli.addListener('line', function(code) {
if (code && code !== '.history') {
fs.write(fd, code + '\n');
} else {
repl.rli.historyIndex++;
repl.rli.history.pop();
}
});
process.on('exit', function() {
fs.closeSync(fd);
});
repl.commands['.history'] = {
help : 'Show the history',
action : function() {
var out = [];
repl.rli.history.forEach(function(v, k) {
out.push(v);
});
repl.outputStream.write(out.reverse().join('\n') + '\n');
repl.displayPrompt();
}
};
}; |
Fix checkbox id to take form prefix into account. | (function($) {
'use strict';
var $parent = $('#apps-newsletter-subscribe');
var $checkbox = $parent.find('#id_newsletter-newsletter');
var $settings = $parent.find('.newsletter-setting');
var $agree = $parent.find('#id_agree');
var required = 'required';
if(!$checkbox.is(':checked')) {
$settings.hide(0);
$agree.removeAttr(required);
}
$checkbox.on('click', function() {
if($checkbox.is(':checked')) {
$settings.fadeIn();
$agree.attr(required, required);
} else {
$settings.fadeOut();
$agree.removeAttr(required);
}
});
})(jQuery);
| (function($) {
'use strict';
var $parent = $('#apps-newsletter-subscribe');
var $checkbox = $parent.find('#id_newsletter');
var $settings = $parent.find('.newsletter-setting');
var $agree = $parent.find('#id_agree');
var required = 'required';
if(!$checkbox.is(':checked')) {
$settings.hide(0);
$agree.removeAttr(required);
}
$checkbox.on('click', function() {
if($checkbox.is(':checked')) {
$settings.fadeIn();
$agree.attr(required, required);
} else {
$settings.fadeOut();
$agree.removeAttr(required);
}
});
})(jQuery);
|
Include start date, end date, and active flag in comics list | from django.contrib import admin
from comics.core import models
class ComicAdmin(admin.ModelAdmin):
list_display = ('slug', 'name', 'language', 'url', 'rights', 'start_date',
'end_date', 'active')
prepopulated_fields = {
'slug': ('name',)
}
class ReleaseAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'comic', 'pub_date', 'fetched')
list_filter = ['pub_date', 'fetched', 'comic']
date_hierarchy = 'pub_date'
exclude = ('images',)
class ImageAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'file', 'height', 'width', 'fetched', 'title', 'text')
list_filter = ['fetched', 'comic']
date_hierarchy = 'fetched'
admin.site.register(models.Comic, ComicAdmin)
admin.site.register(models.Release, ReleaseAdmin)
admin.site.register(models.Image, ImageAdmin)
| from django.contrib import admin
from comics.core import models
class ComicAdmin(admin.ModelAdmin):
list_display = ('slug', 'name', 'language', 'url', 'rights')
prepopulated_fields = {
'slug': ('name',)
}
class ReleaseAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'comic', 'pub_date', 'fetched')
list_filter = ['pub_date', 'fetched', 'comic']
date_hierarchy = 'pub_date'
exclude = ('images',)
class ImageAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'file', 'height', 'width', 'fetched', 'title', 'text')
list_filter = ['fetched', 'comic']
date_hierarchy = 'fetched'
admin.site.register(models.Comic, ComicAdmin)
admin.site.register(models.Release, ReleaseAdmin)
admin.site.register(models.Image, ImageAdmin)
|
Test commit from codeenvy IDE... PREPARE FOR CODING FROM SCHOOL! | package com.slickjava.rook;
import com.slickjava.rook.map.Map;
import com.slickjava.rook.map.tile.TileManager;
import com.slickjava.rook.net.MainServer;
import com.slickjava.rook.player.PlayerManager;
public class Server {
public static int port = 4444;
public static final double ROOK_VERSION = 0.1;
public static String mapName = "Test";
public static Map gameMap;
public static MainServer server;
public static PlayerManager playerManager;
public static void main(String args[])
{
Server server = new Server();
server.init();
}
public void init()
{
//Test commit from codeenvy IDE.... yay!! let's hope I can code at school now :D
//Next two lines are for testing only.
playerManager = new PlayerManager();
gameMap = new Map(mapName, 100, 100);
server = new MainServer();
System.out.println(gameMap.getTileByCoord(5, 78).getTileName());
}
public static MainServer getMainServer()
{
return server;
}
public static Map getMap()
{
return gameMap;
}
}
| package com.slickjava.rook;
import com.slickjava.rook.map.Map;
import com.slickjava.rook.map.tile.TileManager;
import com.slickjava.rook.net.MainServer;
import com.slickjava.rook.player.PlayerManager;
public class Server {
public static int port = 4444;
public static final double ROOK_VERSION = 0.1;
public static String mapName = "Test";
public static Map gameMap;
public static MainServer server;
public static PlayerManager playerManager;
public static void main(String args[])
{
Server server = new Server();
server.init();
}
public void init()
{
//Next two lines are for testing only.
playerManager = new PlayerManager();
gameMap = new Map(mapName, 100, 100);
server = new MainServer();
System.out.println(gameMap.getTileByCoord(5, 78).getTileName());
}
public static MainServer getMainServer()
{
return server;
}
public static Map getMap()
{
return gameMap;
}
}
|
Create align data when creating table | var Immutable = require('immutable');
var Draft = require('draft-js');
var TYPES = require('./TYPES');
var createRow = require('./createRow');
/**
* Create a new table header
*
* @param {String} tableKey
* @param {Number} countColumns
* @return {OrderedMap<String:Draft.ContentBlock>}
*/
function createHeader(tableKey, countColumns) {
var tableHeaderKey = Draft.genNestedKey(tableKey);
var tableHeaderBlock = new Draft.ContentBlock({
key: tableHeaderKey,
type: TYPES.HEADER,
data: Immutable.Map({
align: Array
.apply(null, Array(10))
.map(function(){ return TYPES.LEFT; })
})
});
return Immutable.OrderedMap([
[tableHeaderKey, tableHeaderBlock]
])
.merge(
createRow(tableHeaderKey, countColumns)
);
}
module.exports = createHeader;
| var Immutable = require('immutable');
var Draft = require('draft-js');
var TYPES = require('./TYPES');
var createRow = require('./createRow');
/**
* Create a new table header
*
* @param {String} tableKey
* @param {Number} countColumns
* @return {OrderedMap<String:Draft.ContentBlock>}
*/
function createHeader(tableKey, countColumns) {
var tableHeaderKey = Draft.genNestedKey(tableKey);
var tableHeaderBlock = new Draft.ContentBlock({
key: tableHeaderKey,
type: TYPES.HEADER
});
return Immutable.OrderedMap([
[tableHeaderKey, tableHeaderBlock]
])
.merge(
createRow(tableHeaderKey, countColumns)
);
}
module.exports = createHeader;
|
Remove an unused property set. | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.layout',
name: 'Section',
requires: [
'foam.core.Action',
'foam.core.Property'
],
properties: [
{
class: 'Function',
name: 'isAvailable',
value: function() { return true; }
},
{
class: 'String',
name: 'title'
},
{
class: 'FObjectArray',
of: 'foam.core.Property',
name: 'properties'
},
{
class: 'FObjectArray',
of: 'foam.core.Action',
name: 'actions'
}
],
methods: [
function fromSectionAxiom(a, cls) {
this.copyFrom({
isAvailable: a.isAvailable,
title: a.title,
properties: cls.getAxiomsByClass(this.Property)
.filter(p => p.section == a.name)
.filter(p => ! p.hidden),
actions: cls.getAxiomsByClass(this.Action)
.filter(a => a.section == a.name)
});
return this;
}
]
}); | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.layout',
name: 'Section',
requires: [
'foam.core.Action',
'foam.core.Property'
],
properties: [
{
class: 'Function',
name: 'isAvailable',
value: function() { return true; }
},
{
class: 'String',
name: 'title'
},
{
class: 'FObjectArray',
of: 'foam.core.Property',
name: 'properties'
},
{
class: 'FObjectArray',
of: 'foam.core.Action',
name: 'actions'
}
],
methods: [
function fromSectionAxiom(a, cls) {
this.copyFrom({
isAvailable: a.isAvailable,
order: a.order,
title: a.title,
properties: cls.getAxiomsByClass(this.Property)
.filter(p => p.section == a.name)
.filter(p => ! p.hidden),
actions: cls.getAxiomsByClass(this.Action)
.filter(a => a.section == a.name)
});
return this;
}
]
}); |
[1.4][sfSympalPlugin][0.7] Fix so we only enable markdown editor for Markdown slot types
git-svn-id: fb4b88f168106301dda01b59a7b997f753c86fb4@25946 ee427ae8-e902-0410-961c-c3ed070cd9f9 | <?php include_stylesheets_for_form($form) ?>
<?php include_javascripts_for_form($form) ?>
<span id="sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form" class="sympal_<?php echo sfInflector::tableize($contentSlot->getType()) ?>_content_slot_editor_form">
<?php echo $form->renderHiddenFields() ?>
<?php if ($contentSlot->getIsColumn()): ?>
<?php if (sfSympalConfig::isI18nEnabled('sfSympalContentSlot') && !isset($form[$contentSlot->getName()])): ?>
<?php echo $form[$sf_user->getCulture()][$contentSlot->getName()] ?>
<?php else: ?>
<?php echo $form[$contentSlot->getName()] ?>
<?php endif; ?>
<?php else: ?>
<?php if (sfSympalConfig::isI18nEnabled('sfSympalContentSlot')): ?>
<?php echo $form[$sf_user->getCulture()]['value'] ?>
<?php else: ?>
<?php echo $form['value'] ?>
<?php endif; ?>
<?php endif; ?>
</span>
<script type="text/javascript">
<?php if ($contentSlot->getType() == 'Markdown'): ?>
$('#sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form textarea').markItUp(mySettings);
<?php endif; ?>
$('#sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form textarea').elastic();
</script> | <?php include_stylesheets_for_form($form) ?>
<?php include_javascripts_for_form($form) ?>
<span id="sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form" class="sympal_<?php echo sfInflector::tableize($contentSlot->getType()) ?>_content_slot_editor_form">
<?php echo $form->renderHiddenFields() ?>
<?php if ($contentSlot->getIsColumn()): ?>
<?php if (sfSympalConfig::isI18nEnabled('sfSympalContentSlot') && !isset($form[$contentSlot->getName()])): ?>
<?php echo $form[$sf_user->getCulture()][$contentSlot->getName()] ?>
<?php else: ?>
<?php echo $form[$contentSlot->getName()] ?>
<?php endif; ?>
<?php else: ?>
<?php if (sfSympalConfig::isI18nEnabled('sfSympalContentSlot')): ?>
<?php echo $form[$sf_user->getCulture()]['value'] ?>
<?php else: ?>
<?php echo $form['value'] ?>
<?php endif; ?>
<?php endif; ?>
</span>
<script type="text/javascript">
$('#sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form textarea').markItUp(mySettings);
$('#sympal_content_slot_<?php echo $contentSlot->getId() ?>_editor_form').elastic();
</script> |
Remove comment looking forward to Vespa 6. | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.fastsearch;
import com.yahoo.data.access.Inspector;
import com.yahoo.data.access.Type;
import com.yahoo.prelude.hitfield.XMLString;
import com.yahoo.search.result.PositionsData;
/**
* Class converting data (historically XML-encoded) from a document summary field.
* This has only been used to represent geographical positions.
* @author Steinar Knutsen
*/
public class XMLField extends DocsumField {
public XMLField(String name) {
super(name);
}
private Object convert(String value) {
return new XMLString(value);
}
@Override
public String toString() {
return "field " + getName() + " type XMLString";
}
@Override
public Object convert(Inspector value) {
if (value.type() == Type.OBJECT || value.type() == Type.ARRAY) {
return new PositionsData(value);
}
return convert(value.asString(""));
}
}
| // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.fastsearch;
import com.yahoo.data.access.Inspector;
import com.yahoo.data.access.Type;
import com.yahoo.prelude.hitfield.XMLString;
import com.yahoo.search.result.PositionsData;
/**
* Class converting data (historically XML-encoded) from a document summary field.
* This has only been used to represent geographical positions.
* @author Steinar Knutsen
*/
public class XMLField extends DocsumField {
public XMLField(String name) {
super(name);
}
private Object convert(String value) {
return new XMLString(value);
}
@Override
public String toString() {
return "field " + getName() + " type XMLString";
}
@Override
public Object convert(Inspector value) {
/* In Vespa 6 the backend will send an XML-formatted string to represent
* positions data. This will change in next version to sending an object
* or an array of objects instead, suitable for the PositionsData class.
*/
if (value.type() == Type.OBJECT || value.type() == Type.ARRAY) {
return new PositionsData(value);
}
return convert(value.asString(""));
}
}
|
Add User-Agent for GitHub calls. | var fs = require('fs');
var url = require('url');
var request = require('request');
var package = require('../package.json');
/**
* @class
*/
var Procure = function() {};
/**
* "Procure" a resource, whether local or remote.
* @function procure
* @param {string} uri Some path to a file.
* @param {Procure~ProcuringComplete} callback Function called on sucess or failure.
*/
Procure.prototype.procure = function( uri , procured ) {
var info = url.parse( uri );
if (~['http:', 'https:'].indexOf( info.protocol )) {
request({
uri: uri,
headers: {
'Accept': 'application/json;q=0.9,*/*;q=0.8',
'User-Agent': 'procure/' + package.version
}
}, function(err, res, body) {
var statusCode = res.statusCode;
if (statusCode != 200 ) return procured('non-200 response ' + statusCode);
return procured( err , body );
});
} else {
fs.readFile( uri , procured );
}
};
/**
* The callback function when the file is retrieved (or not).
* @callback Procure~ProcuringComplete
* @param {mixed} err Error message, if any. Null / undefined if none.
* @param {string} body Body of the requested content.
*/
module.exports = Procure;
| var fs = require('fs');
var url = require('url');
var request = require('request');
/**
* @class
*/
var Procure = function() {};
/**
* "Procure" a resource, whether local or remote.
* @function procure
* @param {string} uri Some path to a file.
* @param {Procure~ProcuringComplete} callback Function called on sucess or failure.
*/
Procure.prototype.procure = function( uri , procured ) {
var info = url.parse( uri );
if (~['http:', 'https:'].indexOf( info.protocol )) {
request({
uri: uri,
headers: {
'Accept': 'application/json;q=0.9,*/*;q=0.8'
}
}, function(err, res, body) {
if (res.statusCode != 200 ) return procured('non-200 response');
return procured( err , body );
});
} else {
fs.readFile( uri , procured );
}
};
/**
* The callback function when the file is retrieved (or not).
* @callback Procure~ProcuringComplete
* @param {mixed} err Error message, if any. Null / undefined if none.
* @param {string} body Body of the requested content.
*/
module.exports = Procure;
|
Add all_nodes and growing times param | class GrowingGraph:
def __init__(self, neighbors_table, start_nodes):
self.neighbors_table = neighbors_table
self.outer_nodes = set(start_nodes)
self.inner_nodes = set()
def all_nodes(self):
return self.outer_nodes | self.inner_nodes
def growing(self, times=1):
for _ in range(times):
for old_node in self.outer_nodes.copy():
self._update_nodes(old_node)
def _update_nodes(self, old_node):
new_nodes = set(self.neighbors_table[old_node])
if new_nodes:
self.outer_nodes.remove(old_node)
self.inner_nodes.add(old_node)
for new_node in new_nodes:
if new_node not in self.inner_nodes:
self.outer_nodes.add(new_node)
def __str__(self):
return 'GrowingGraph(out:{}, in:{})'.format(
self.outer_nodes, self.inner_nodes
) | class GrowingGraph:
def __init__(self, neighbors_table, start_nodes):
self.neighbors_table = neighbors_table
self.outer_nodes = set(start_nodes)
self.inner_nodes = set()
def growing(self):
for old_node in self.outer_nodes.copy():
self._update_nodes(old_node)
def _update_nodes(self, old_node):
new_nodes = set(self.neighbors_table[old_node])
if new_nodes:
self.outer_nodes.remove(old_node)
self.inner_nodes.add(old_node)
for new_node in new_nodes:
if new_node not in self.inner_nodes:
self.outer_nodes.add(new_node)
def __str__(self):
return f'GrowingGraph(out:{self.outer_nodes}, in:{self.inner_nodes})' |
Set Content-Type header to ensure we're sending javascript | package main
import (
"fmt"
"log"
"net/http"
"net/url"
"time"
"github.com/zenazn/goji"
)
func ping(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/javascript")
fmt.Fprintf(w, "(function(){})();")
referrer := r.Referer()
if referrer == "" {
return
}
url, err := url.Parse(referrer)
if err != nil {
http.Error(w, "Couldn't parse "+referrer+": "+err.Error(), 500)
return
}
var ip string
if res := r.Header.Get("X-Forwarded-For"); res != "" {
ip = res
log.Println("Fetching IP from proxy: ", ip)
} else {
ip = r.RemoteAddr
}
visit := &Visit{
IP: ip,
Host: url.Host,
Path: url.Path,
CreatedAt: time.Now().UTC().Format(time.RFC3339),
}
log.Println("Logging visit:", visit.String())
err = visit.Save()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func main() {
goji.Get("/ping", ping)
goji.Get("/ping.js", ping)
goji.Serve()
}
| package main
import (
"fmt"
"log"
"net/http"
"net/url"
"time"
"github.com/zenazn/goji"
)
func ping(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "")
referrer := r.Referer()
if referrer == "" {
return
}
url, err := url.Parse(referrer)
if err != nil {
http.Error(w, "Couldn't parse "+referrer+": "+err.Error(), 500)
return
}
var ip string
if res := r.Header.Get("X-Forwarded-For"); res != "" {
ip = res
log.Println("Fetching IP from proxy: ", ip)
} else {
ip = r.RemoteAddr
}
visit := &Visit{
IP: ip,
Host: url.Host,
Path: url.Path,
CreatedAt: time.Now().UTC().Format(time.RFC3339),
}
log.Println("Logging visit:", visit.String())
err = visit.Save()
if err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func main() {
goji.Get("/ping", ping)
goji.Get("/ping.js", ping)
goji.Serve()
}
|
Set the modification dates of the created files to that of the notes | import os, sys, json
from simperium.core import Api as SimperiumApi
appname = 'chalk-bump-f49' # Simplenote
token = os.environ['TOKEN']
backup_dir = sys.argv[1] if len(sys.argv) > 1 else (os.path.join(os.environ['HOME'], "Dropbox/SimplenoteBackups"))
print "Starting backup your simplenote to: %s" % backup_dir
if not os.path.exists(backup_dir):
print "Creating directory: %s" % backup_dir
os.makedirs(backup_dir)
api = SimperiumApi(appname, token)
#print token
notes = api.note.index(data=True)
for note in notes['index']:
path = os.path.join(backup_dir, note['id'] + '.txt')
#print path
with open(path, "w") as f:
# print json.dumps(note, indent=2)
#f.write("id: %s\n" % note['id'])
f.write(note['d']['content'].encode('utf8'))
f.write("\n")
f.write("Tags: %s\n" % ", ".join(note['d']['tags']).encode('utf8'))
os.utime(path,(note['d']['modificationDate'],note['d']['modificationDate']))
print "Done: %d files." % len(notes['index'])
| import os, sys, json
from simperium.core import Api as SimperiumApi
appname = 'chalk-bump-f49' # Simplenote
token = os.environ['TOKEN']
backup_dir = sys.argv[1] if len(sys.argv) > 1 else (os.path.join(os.environ['HOME'], "Dropbox/SimplenoteBackups"))
print "Starting backup your simplenote to: %s" % backup_dir
if not os.path.exists(backup_dir):
print "Creating directory: %s" % backup_dir
os.makedirs(backup_dir)
api = SimperiumApi(appname, token)
#print token
notes = api.note.index(data=True)
for note in notes['index']:
path = os.path.join(backup_dir, note['id'] + '.txt')
#print path
with open(path, "w") as f:
# print json.dumps(note, indent=2)
#f.write("id: %s\n" % note['id'])
f.write(note['d']['content'].encode('utf8'))
f.write("\n")
f.write("Tags: %s\n" % ", ".join(note['d']['tags']).encode('utf8'))
print "Done: %d files." % len(notes['index'])
|
Add anchors to the value of "NAME" and "URL", respectively | $(function() {
$("#result").hide();
$("#search_button").on("click", function() {
var name = $("#name").val();
var score = $("#score").val();
var url = "/api/endpoints/search/?name=" + name + "&score=" + score;
$.getJSON(url, function(data) {
$("#result").show();
for (var i = 0; i < data.length; i++) {
var endpoint = data[i];
var row = $("<tr>");
row.append($("<td>").append($("<a>").attr("href", "/endpoints/" + endpoint.id).text(endpoint.name)));
row.append($("<td>").append($("<a>").attr("href", endpoint.url).text(endpoint.url)));
row.append($("<td>").text(endpoint.evaluation.score));
$("#result_body").append(row);
}
});
});
});
| $(function() {
$("#result").hide();
$("#search_button").on("click", function() {
var name = $("#name").val();
var score = $("#score").val();
var url = "/api/endpoints/search/?name=" + name + "&score=" + score;
$.getJSON(url, function(data) {
$("#result").show();
for (var i = 0; i < data.length; i++) {
var row = $("<tr>");
row.append($("<td>").text(data[i].name));
row.append($("<td>").text(data[i].url));
row.append($("<td>").text(data[i].evaluation.score));
$("#result_body").append(row);
}
});
});
});
|
Change package url to point to opusonesolutions group | from setuptools import setup
def readme():
with open("README.rst", 'r') as f:
return f.read()
setup(
name="asciigraf",
version="0.3.0",
packages=["asciigraf"],
description="A python library for making ascii-art into network graphs.",
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Software Development :: Libraries :: Python Modules",
],
long_description=readme(),
author="Opus One Solutions",
author_email="rnd@opusonesolutions.com",
url="https://github.com/opusonesolutions/asciigraf",
keywords=["graph", "network", "testing", "parser"],
license="MIT",
install_requires=[
'networkx==1.11',
],
extras_require={
"test": ["pytest", "pytest-cov"],
},
)
| from setuptools import setup
def readme():
with open("README.rst", 'r') as f:
return f.read()
setup(
name="asciigraf",
version="0.3.0",
packages=["asciigraf"],
description="A python library for making ascii-art into network graphs.",
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Software Development :: Libraries :: Python Modules",
],
long_description=readme(),
author="Opus One Solutions",
author_email="rnd@opusonesolutions.com",
url="https://github.com/AnjoMan/asciigraf",
keywords=["graph", "network", "testing", "parser"],
license="MIT",
install_requires=[
'networkx==1.11',
],
extras_require={
"test": ["pytest", "pytest-cov"],
},
)
|
Fix fatal error when a dependency needs to be installed
```
PHP Catchable fatal error: Argument 1 passed to
Composer\DependencyResolver\Rule::getPrettyString() must be an instance
of Composer\DependencyResolver\Pool, none given, called in
/home/vagrant/.wp-cli/php/WP_CLI/PackageManagerEventSubscriber.php on
line 40 and defined in
/home/vagrant/.wp-cli/vendor/composer/composer/src/Composer/DependencyResolver/Rule.php
on line 161
``` | <?php
namespace WP_CLI;
use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Script\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;
/**
* A Composer Event subscriber so we can keep track of what's happening inside Composer
*/
class PackageManagerEventSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return array(
ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
);
}
public static function pre_install( PackageEvent $event ) {
WP_CLI::log( ' - Installing package' );
}
public static function post_install( PackageEvent $event ) {
$operation = $event->getOperation();
$reason = $operation->getReason();
if ( $reason instanceof Rule ) {
switch ( $reason->getReason() ) {
case Rule::RULE_PACKAGE_CONFLICT;
case Rule::RULE_PACKAGE_SAME_NAME:
case Rule::RULE_PACKAGE_REQUIRES:
$composer_error = $reason->getPrettyString( $event->getPool() );
break;
}
if ( ! empty( $composer_error ) ) {
WP_CLI::log( sprintf( " - Error: %s", $composer_error ) );
}
}
}
}
| <?php
namespace WP_CLI;
use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Script\PackageEvent;
use \Composer\Script\ScriptEvents;
use \WP_CLI;
/**
* A Composer Event subscriber so we can keep track of what's happening inside Composer
*/
class PackageManagerEventSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return array(
ScriptEvents::PRE_PACKAGE_INSTALL => 'pre_install',
ScriptEvents::POST_PACKAGE_INSTALL => 'post_install',
);
}
public static function pre_install( PackageEvent $event ) {
WP_CLI::log( ' - Installing package' );
}
public static function post_install( PackageEvent $event ) {
$operation = $event->getOperation();
$reason = $operation->getReason();
if ( $reason instanceof Rule ) {
switch ( $reason->getReason() ) {
case Rule::RULE_PACKAGE_CONFLICT;
case Rule::RULE_PACKAGE_SAME_NAME:
case Rule::RULE_PACKAGE_REQUIRES:
$composer_error = $reason->getPrettyString();
break;
}
if ( ! empty( $composer_error ) ) {
WP_CLI::log( sprintf( " - Error: %s", $composer_error ) );
}
}
}
}
|
Add simplejson as a requirement for the plugin. | from setuptools import setup
import backlog
PACKAGE = 'TracBacklog'
setup(name=PACKAGE,
version=backlog.get_version(),
packages=['backlog'],
package_data={
'backlog': [
'htdocs/css/*.css',
'htdocs/img/*.png',
'htdocs/js/*.js',
'htdocs/js/dojo/*.js',
'htdocs/js/dojo/dnd/*.js',
'htdocs/js/dojo/date/*.js',
'htdocs/js/dojo/fx/*.js',
'templates/*.html',
'scripts/*'
]},
entry_points={
'trac.plugins': ['backlog = backlog.web_ui']
},
install_requires=[
'simplejson>=2.0',
]
)
| from setuptools import setup
import backlog
PACKAGE = 'TracBacklog'
setup(name=PACKAGE,
version=backlog.get_version(),
packages=['backlog'],
package_data={
'backlog': [
'htdocs/css/*.css',
'htdocs/img/*.png',
'htdocs/js/*.js',
'htdocs/js/dojo/*.js',
'htdocs/js/dojo/dnd/*.js',
'htdocs/js/dojo/date/*.js',
'htdocs/js/dojo/fx/*.js',
'templates/*.html',
'scripts/*'
]},
entry_points={
'trac.plugins': ['backlog = backlog.web_ui']
}
)
|
Remove copy_file call because it doesn't work right with bdist_deb | #!/usr/bin/env python
from distutils.core import setup
from distutils.file_util import copy_file
import platform
version = "0.1.0"
setup(name="riemann-sumd",
version=version,
description="Python agent for scheduling event generating processes and sending the results to Riemann",
author="Brian Hatfield",
author_email="bmhatfield@gmail.com",
url="https://github.com/bmhatfield/riemann-sumd",
package_dir={'': 'lib'},
py_modules=['event', 'loader', 'scheduler', 'sender', 'task'],
data_files=[('/etc/init/', ["init/ubuntu/sumd.conf"]),
('/etc/sumd', ['examples/etc/sumd/sumd.conf']),
('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']),
('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])],
scripts=["bin/sumd"]
) | #!/usr/bin/env python
from distutils.core import setup
from distutils.file_util import copy_file
import platform
version = "0.1.0"
setup(name="riemann-sumd",
version=version,
description="Python agent for scheduling event generating processes and sending the results to Riemann",
author="Brian Hatfield",
author_email="bmhatfield@gmail.com",
url="https://github.com/bmhatfield/riemann-sumd",
package_dir={'': 'lib'},
py_modules=['event', 'loader', 'scheduler', 'sender', 'task'],
data_files=[('/etc/init/', ["init/ubuntu/sumd.conf"]),
('/etc/sumd', ['examples/etc/sumd/sumd.conf']),
('/etc/sumd/tasks.d', ['examples/etc/sumd/tasks.d/simple.task.example']),
('/etc/sumd/tags.d', ['examples/etc/sumd/tags.d/simple.tag.example'])],
scripts=["bin/sumd"]
)
copy_file('/lib/init/upstart-job', '/etc/init.d/sumd', link='sym') |
Fix the exception logger to actually log to stdout | import sys
import traceback
class ExceptionLogger(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
try:
return self.app(environ, start_response)
except Exception:
(exc_type, exc_value, trace) = sys.exc_info()
traceback.print_exception(exc_type,
exc_value,
trace,
file=sys.stdout)
raise
| import sys
import traceback
class ExceptionLogger(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
try:
return self.app(environ, start_response)
except Exception:
(exc_type, exc_value, trace) = sys.exc_info()
traceback.print_exception(exc_type,
exc_value,
trace,
sys.stdout)
raise
|
Put temp files in ~/tmp by default | """Show a command to edit fred files"""
import os
import sys
from dotsite.paths import makepath, pwd
def get_freds(paths):
if not paths:
paths = ['~/tmp']
result = set()
for path in paths:
path = makepath(path)
if path.isdir():
result |= {p for p in path.files('fred*') if p[-1] != '~'}
elif path.isfile() and path.name.startswith('fred'):
result.add(path)
return [pwd().relpathto(p) for p in result]
def main(args):
freds = get_freds(args)
if not freds:
return not os.EX_OK
print 'v %s' % ' '.join(freds)
return os.EX_OK
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| """Show a command to edit fred files"""
import os
import sys
from dotsite.paths import makepath, pwd
def get_freds(paths):
if not paths:
paths = ['.']
result = set()
for path in paths:
path = makepath(path)
if path.isdir():
result |= {p for p in path.files('fred*') if p[-1] != '~'}
elif path.isfile() and path.name.startswith('fred'):
result.add(path)
return [pwd().relpathto(p) for p in result]
def main(args):
freds = get_freds(args)
if not freds:
return not os.EX_OK
print 'v %s' % ' '.join(freds)
return os.EX_OK
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
|
Add toString method for debuging purposes | package pl.koszela.jan.domain;
import java.util.Objects;
/**
* Created on 12.08.2017.
*
* @author Jan Koszela
*/
public class Order {
private Product product;
private int quantity;
public Order(String productName, int quantity) {
this.product = Product.builder()
.item(productName)
.build();
this.quantity = quantity;
}
public Product getProduct() {
return this.product;
}
public int getQuantity() {
return this.quantity;
}
public void setProduct(Product productName) {
this.product = productName;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return Objects.equals(product, order.product);
}
@Override
public int hashCode() {
return Objects.hash(product, quantity);
}
@Override
public String toString() {
return "Order{" +
"productName='" + product + '\'' +
", quantity=" + quantity +
'}';
}
}
| package pl.koszela.jan.domain;
import java.util.Objects;
/**
* Created on 12.08.2017.
*
* @author Jan Koszela
*/
public class Order {
private String productName;
private int quantity;
public Order(String productName, int quantity) {
this.productName = productName;
this.quantity = quantity;
}
public String getProductName() {
return this.productName;
}
public int getQuantity() {
return this.quantity;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return Objects.equals(productName, order.productName);
}
@Override
public int hashCode() {
return Objects.hash(productName, quantity);
}
}
|
Make getshell test more reliable.
This test now uses the 'contact' doc from the standard asset set. While
still not guaranteed to be present, this is a significant improvement
from the previous ad-hoc test document, which required it be manually
added to the local repo ahead of time. | package shell
import (
"bytes"
"fmt"
"os"
"testing"
)
func TestCat(t *testing.T) {
myShell, err := NewShell()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
reader, err := myShell.Cat("QmYCvbfNbCwFR45HiNP45rwJgvatpiW38D961L5qAhUM5Y")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
buf := new(bytes.Buffer)
buf.ReadFrom(reader)
output := buf.String()
expected := `Come hang out in our IRC chat room if you have any questions.
Contact the ipfs dev team:
- Bugs: https://github.com/ipfs/go-ipfs/issues
- Help: irc.freenode.org/#ipfs
- Email: dev@ipfs.io
`
if output != expected {
t.FailNow()
}
}
| package shell
import (
"bytes"
"fmt"
"os"
"testing"
)
func TestCat(t *testing.T) {
myShell, err := NewShell()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
reader, err := myShell.Cat("QmQLBvJ3ur7U7mzbYDLid7WkaciY84SLpPYpGPHhDNps2Y")
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
buf := new(bytes.Buffer)
buf.ReadFrom(reader)
output := buf.String()
expected := "\"The man who makes no mistakes does not make anything.\" - Edward John Phelps\n"
if output != expected {
t.FailNow()
}
}
|
Change to use dirname instead of __DIR__ | <?php
class SiteController extends Controller
{
public $layout = 'column1';
/**
* Displays the front page.
*/
public function actionIndex()
{
$this->redirect(array('/auth/assignment/index'));
}
/**
* Resets the database for the demo application.
*/
public function actionReset()
{
/* @var $db CDbConnection */
$db = Yii::app()->getComponent('db');
$filename = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'schema.sql';
if (file_exists($filename))
{
$schema = file_get_contents($filename);
$schema = preg_split("/;\s+/", trim($schema, ';'));
foreach ($schema as $sql)
$db->createCommand($sql)->execute();
}
Yii::app()->user->setFlash('success', 'Demo reset.');
$this->redirect(array('index'));
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if ($error = Yii::app()->errorHandler->error)
{
if (Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
} | <?php
class SiteController extends Controller
{
public $layout = 'column1';
/**
* Displays the front page.
*/
public function actionIndex()
{
$this->redirect(array('/auth/assignment/index'));
}
/**
* Resets the database for the demo application.
*/
public function actionReset()
{
/* @var $db CDbConnection */
$db = Yii::app()->getComponent('db');
$filename = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'schema.sql';
if (file_exists($filename))
{
$schema = file_get_contents($filename);
$schema = preg_split("/;\s+/", trim($schema, ';'));
foreach ($schema as $sql)
$db->createCommand($sql)->execute();
}
Yii::app()->user->setFlash('success', 'Demo reset.');
$this->redirect(array('index'));
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if ($error = Yii::app()->errorHandler->error)
{
if (Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
} |
Make sure to return the wsgi app | import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
# Include the transaction manager
config.include('pyramid_tm')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('main',
'/*traverse',
use_global_views=True
)
return config.make_wsgi_app()
| import logging
log = logging.getLogger(__name__)
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
from .models import DBSession
required_settings = [
'pyramid.secret.session',
'pyramid.secret.auth',
]
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
config = Configurator(settings=settings)
do_start = True
for _req in required_settings:
if _req not in settings:
log.error('{} is not set in configuration file.'.format(_req))
do_start = False
if do_start is False:
log.error('Unable to start due to missing configuration')
exit(-1)
# Include the transaction manager
config.include('pyramid_tm')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('main',
'/*traverse',
use_global_views=True
)
|
Exclude GA if Do Not Track is set | document.addEventListener("DOMContentLoaded", (event) => {
const images = ["hello1.jpeg", "hello2.jpeg", "hello3.jpeg", "hello4.jpeg", "hello5.jpeg", "hello6.jpeg"];
const todaysImage = images[(new Date().getDate() % images.length)];
const image = document.getElementById("profile");
image.setAttribute("src", "assets/" + todaysImage);
});
if (["0", "unspecified"].includes(navigator.doNotTrack)) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-64774283-2', 'auto');
ga('send', 'pageview');
}
| document.addEventListener("DOMContentLoaded", (event) => {
const images = ["hello1.jpeg", "hello2.jpeg", "hello3.jpeg", "hello4.jpeg", "hello5.jpeg", "hello6.jpeg"];
const todaysImage = images[(new Date().getDate() % images.length)];
const image = document.getElementById("profile");
image.setAttribute("src", "assets/" + todaysImage);
});
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-64774283-2', 'auto');
ga('send', 'pageview');
|
Fix legacy upgrade with missing instance
If the user is trying to upgrade their account and for some reason the
instance has been deleted in the meantime then we simply redirect to the
main listing of instances. | "use strict";
var format = require('util').format;
var config = require('config');
function upgradeLegacyAccount(req, res, next) {
if (!req.session.legacyInstanceId) {
return next();
}
// User is trying to upgrade their account
var instanceId = req.session.legacyInstanceId;
delete req.session.legacyInstanceId;
var Permission = req.popit.permissions();
Permission.create({
account: req.user.id,
instance: instanceId,
role: 'owner',
}, function(err) {
if (err) {
return next(err);
}
req.flash('info', 'Account successfully upgraded');
var Instance = req.popit.master().model('Instance');
Instance.findById(instanceId, function(err, instance) {
if (err) {
return next(err);
}
if (!instance) {
return res.redirect('/instances');
}
// Redirect to the instance the user was trying to log into
res.redirect(format(config.instance_server.base_url_format, instance.slug));
});
});
}
module.exports = upgradeLegacyAccount;
| "use strict";
var format = require('util').format;
var config = require('config');
function upgradeLegacyAccount(req, res, next) {
if (!req.session.legacyInstanceId) {
return next();
}
// User is trying to upgrade their account
var instanceId = req.session.legacyInstanceId;
delete req.session.legacyInstanceId;
var Permission = req.popit.permissions();
Permission.create({
account: req.user.id,
instance: instanceId,
role: 'owner',
}, function(err) {
if (err) {
return next(err);
}
req.flash('info', 'Account successfully upgraded');
var Instance = req.popit.master().model('Instance');
Instance.findById(instanceId, function(err, instance) {
if (err) {
return next(err);
}
// Redirect to the instance the user was trying to log into
res.redirect(format(config.instance_server.base_url_format, instance.slug));
});
});
}
module.exports = upgradeLegacyAccount;
|
Fix bug where modal doesn't disappear on delete | Template['modifyBookModal'].helpers({
header: function() {
if (Session.get('modifyBookModal.doc')) {
return "Modify book";
} else {
return "Add a new book";
}
},
type: function() {
return Session.get('modifyBookModal.doc') ? 'update' : 'insert';
},
doc: function() {
return Session.get('modifyBookModal.doc');
},
showDeleteButton: function() {
return !!Session.get('modifyBookModal.doc');
},
categoryOptions: function() {
return Categories.find().map(function(c) {
return { label: c.name, value: c._id };
});
}
});
Template['modifyBookModal'].events({
'click #remove-book-button': function(event, template) {
var book = Session.get('modifyBookModal.doc');
Books.remove(book._id);
$('#modify-book-modal').modal('hide');
}
});
Template['modifyBookModal'].onRendered(function() {
$('#modify-book-modal').modal({
detachable: false,
onShow: function() {
AutoForm.resetForm("modifyBookForm");
}
});
}); | Template['modifyBookModal'].helpers({
header: function() {
if (Session.get('modifyBookModal.doc')) {
return "Modify book";
} else {
return "Add a new book";
}
},
type: function() {
return Session.get('modifyBookModal.doc') ? 'update' : 'insert';
},
doc: function() {
return Session.get('modifyBookModal.doc');
},
showDeleteButton: function() {
return !!Session.get('modifyBookModal.doc');
},
categoryOptions: function() {
return Categories.find().map(function(c) {
return { label: c.name, value: c._id };
});
}
});
Template['modifyBookModal'].events({
'click #remove-book-button': function(event, template) {
var book = Session.get('modifyBookModal.doc');
Books.remove(book._id);
}
});
Template['modifyBookModal'].onRendered(function() {
$('#modify-book-modal').modal({
detachable: false,
onShow: function() {
AutoForm.resetForm("modifyBookForm");
}
});
}); |
Fix Static method should not contain $this reference. | <?php
namespace DigipolisGent\Robo\Task\Deploy\Scp\Factory;
use DigipolisGent\Robo\Task\Deploy\Scp\Adapter\ScpPhpseclibAdapter;
use DigipolisGent\Robo\Task\Deploy\Ssh\Auth\AbstractAuth;
use phpseclib\Net\SCP;
use phpseclib\Net\SSH2;
class ScpPhpseclibFactory implements ScpFactoryInterface
{
public static function create($host, AbstractAuth $auth, $port = 22, $timeout = 10)
{
$ssh = new SSH2($host, $port, $timeout);
$auth->authenticate($ssh);
if (!$ssh->isConnected()) {
throw new \RuntimeException(sprintf(
"ssh: unable to establish connection to %s on port %s",
$host,
$port
));
}
return new ScpPhpseclibAdapter(new SCP($ssh));
}
}
| <?php
namespace DigipolisGent\Robo\Task\Deploy\Scp\Factory;
use DigipolisGent\Robo\Task\Deploy\Scp\Adapter\ScpPhpseclibAdapter;
use DigipolisGent\Robo\Task\Deploy\Ssh\Auth\AbstractAuth;
use phpseclib\Net\SCP;
use phpseclib\Net\SSH2;
class ScpPhpseclibFactory implements ScpFactoryInterface
{
public static function create($host, AbstractAuth $auth, $port = 22, $timeout = 10)
{
$ssh = new SSH2($host, $port, $timeout);
$auth->authenticate($ssh);
if (!$ssh->isConnected()) {
throw new \RuntimeException(sprintf(
"ssh: unable to establish connection to %s on port %s",
$this->host,
$this->port
));
}
return new ScpPhpseclibAdapter(new SCP($ssh));
}
}
|
Add a test for quoted strings with {"quotes"} in .bib files. | from pybtex.database import BibliographyData
from pybtex.core import Entry
from pybtex.database.input.bibtex import Parser
from cStringIO import StringIO
test_data = [
(
'''
''',
BibliographyData(),
),
(
'''@ARTICLE{
test,
title={Polluted
with {DDT}.
},
}''',
BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}),
),
(
'''@ARTICLE{
test,
title="Nested braces and {"quotes"}",
}''',
BibliographyData({u'test': Entry('article', {u'title': 'Nested braces and {"quotes"}'})}),
),
]
def _test(bibtex_input, correct_result):
parser = Parser(encoding='UTF-8')
parser.parse_stream(StringIO(bibtex_input))
result = parser.data
assert result == correct_result
def test_bibtex_parser():
for bibtex_input, correct_result in test_data:
_test(bibtex_input, correct_result)
| from pybtex.database import BibliographyData
from pybtex.core import Entry
from pybtex.database.input.bibtex import Parser
from cStringIO import StringIO
test_data = [
(
'''
''',
BibliographyData(),
),
(
'''@ARTICLE{
test,
title={Polluted
with {DDT}.
},
}''',
BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}),
),
]
def _test(bibtex_input, correct_result):
parser = Parser(encoding='UTF-8')
parser.parse_stream(StringIO(bibtex_input))
result = parser.data
assert result == correct_result
def test_bibtex_parser():
for bibtex_input, correct_result in test_data:
_test(bibtex_input, correct_result)
|
Fix up some issues with supporting schema migration | # Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.
from django.db import models
from django.utils.translation import ugettext_lazy as _
class ActivityStream(models.Model):
'''
Model used to describe activity stream (audit) events
'''
class Meta:
app_label = 'main'
OPERATION_CHOICES = [
('create', _('Entity Created')),
('update', _("Entity Updated")),
('delete', _("Entity Deleted")),
('associate', _("Entity Associated with another Entity")),
('disaassociate', _("Entity was Disassociated with another Entity"))
]
user = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL, related_name='activity_stream')
operation = models.CharField(max_length=9, choices=OPERATION_CHOICES)
timestamp = models.DateTimeField(auto_now_add=True)
changes = models.TextField(blank=True)
object1_id = models.PositiveIntegerField(db_index=True)
object1_type = models.TextField()
object2_id = models.PositiveIntegerField(db_index=True, null=True)
object2_type = models.TextField(null=True, blank=True)
object_relationship_type = models.TextField(blank=True)
| # Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.
from django.db import models
class ActivityStream(models.Model):
'''
Model used to describe activity stream (audit) events
'''
OPERATION_CHOICES = [
('create', _('Entity Created')),
('update', _("Entity Updated")),
('delete', _("Entity Deleted")),
('associate', _("Entity Associated with another Entity")),
('disaassociate', _("Entity was Disassociated with another Entity"))
]
user = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL)
operation = models.CharField(max_length=9, choices=OPERATION_CHOICES)
timestamp = models.DateTimeField(auto_now_add=True)
changes = models.TextField(blank=True)
object1_id = models.PositiveIntegerField(db_index=True)
object1_type = models.TextField()
object2_id = models.PositiveIntegerField(db_index=True)
object2_type = models.TextField()
object_relationship_type = models.TextField()
|
Fix arrow functions should not return assignment | const path = require('path');
const AbstractDataSource = require(path.resolve(__dirname, 'abstract-data-source.js'));
const Twit = require('twit');
class Twitter extends AbstractDataSource {
constructor(config) {
super(config);
this.twitter = new Twit({
consumer_key: config.quote.twitter.consumer_key,
consumer_secret: config.quote.twitter.consumer_secret,
access_token: config.quote.twitter.access_token,
access_token_secret: config.quote.twitter.access_token_secret,
timeout_ms: 60 * 1000,
});
this.twitter.get(
'statuses/user_timeline',
{ screen_name: 'CodeWisdom', exclude_replies: true, count: 10, include_rts: false },
(err, data, response) => { this._data = data.map(tweet => tweet.text); }
);
this._setData(['Retrieving some wisdom...']);
}
getData() {
return this._data[0];
}
_setData(content) {
this._data = content;
}
}
module.exports = Twitter;
| const path = require('path');
const AbstractDataSource = require(path.resolve(__dirname, 'abstract-data-source.js'));
const Twit = require('twit');
class Twitter extends AbstractDataSource {
constructor(config) {
super(config);
this.twitter = new Twit({
consumer_key: config.quote.twitter.consumer_key,
consumer_secret: config.quote.twitter.consumer_secret,
access_token: config.quote.twitter.access_token,
access_token_secret: config.quote.twitter.access_token_secret,
timeout_ms: 60 * 1000,
});
this.twitter.get(
'statuses/user_timeline',
{ screen_name: 'CodeWisdom', exclude_replies: true, count: 10, include_rts: false },
(err, data, response) => this._data = data.map(tweet => tweet.text)
);
this._setData(['Retrieving some wisdom...']);
}
getData() {
return this._data[0];
}
_setData(content) {
this._data = content;
}
}
module.exports = Twitter;
|
fix(seedData): Order of seedData now places the main schema json after all other modules plus refactoring | var path = require('path')
, fs = require('fs')
, packageJson = require(path.resolve(__dirname + '/../../') + '/package.json')
, seedData = {};
function loadSeedDataFile(filePath) {
var data = require(filePath);
Object.keys(data).forEach(function(key) {
if (!!seedData[key]) {
seedData[key] = seedData[key].concat(data[key]);
} else {
seedData[key] = data[key];
}
});
}
packageJson.bundledDependencies.forEach(function(moduleName) {
var filePath = [path.resolve(__dirname + '/../../modules'), moduleName, 'schema', 'seedData.json'].join(path.sep)
if (fs.existsSync(filePath)) {
loadSeedDataFile(filePath);
}
});
loadSeedDataFile(path.resolve(path.join(__dirname, '..', '..', 'schema', 'seedData.json')));
module.exports = seedData; | var path = require( 'path' )
, fs = require( 'fs' )
, fileNames = [ 'seedData' ]
, packageJson = require( path.resolve( __dirname + '/../../' ) + '/package.json' )
, seedData = require( path.resolve( path.join( __dirname, '..', '..', 'schema', 'seedData.json' ) ) );
packageJson.bundledDependencies.forEach(function( moduleName ) {
var moduleConfigPath = [ path.resolve( __dirname + '/../../modules' ), moduleName, 'schema', '' ].join( path.sep );
fileNames.forEach(function( fileName ) {
var filePath = moduleConfigPath + fileName + '.json';
if ( fs.existsSync( filePath ) ) {
var data = require( filePath );
Object.keys( data ).forEach( function( key ) {
if ( !!seedData[ key ] ) {
seedData[ key ] = seedData[ key ].concat( data[ key ] );
} else {
seedData[ key ] = data[ key ];
}
})
}
});
});
module.exports = seedData; |
Clean up un-needed commented line after jkrzywon fixed subprocess bad behaviour | __version__ = "4.0b1"
__build__ = "GIT_COMMIT"
try:
import logging
import subprocess
import os
import platform
FNULL = open(os.devnull, 'w')
if platform.system() == "Windows":
args = ['git', 'describe', '--tags']
else:
args = ['git describe --tags']
git_revision = subprocess.check_output(args,
stderr=FNULL,
shell=True)
__build__ = str(git_revision).strip()
except subprocess.CalledProcessError as cpe:
logging.warning("Error while determining build number\n Using command:\n %s \n Output:\n %s"% (cpe.cmd,cpe.output))
| __version__ = "4.0b1"
__build__ = "GIT_COMMIT"
try:
import logging
import subprocess
import os
import platform
FNULL = open(os.devnull, 'w')
if platform.system() == "Windows":
args = ['git', 'describe', '--tags']
else:
args = ['git describe --tags']
git_revision = subprocess.check_output(args,
#git_revision = subprocess.check_output(['pwd'],
stderr=FNULL,
shell=True)
__build__ = str(git_revision).strip()
except subprocess.CalledProcessError as cpe:
logging.warning("Error while determining build number\n Using command:\n %s \n Output:\n %s"% (cpe.cmd,cpe.output))
|
Add transactional annotation to delete method.
The delete method has to be readOnly=false, otherwise the entities won't be deleted. | package de.terrestris.shogun2.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import de.terrestris.shogun2.model.PersistentObject;
/**
* This abstract service class provides basic CRUD functionality.
*
* @author Nils Bühner
* @see AbstractDaoService
*
*/
public abstract class AbstractCrudService<E extends PersistentObject> extends
AbstractDaoService<E> {
/**
*
* @param e
* @return
*/
@Transactional(readOnly = false)
public E saveOrUpdate(E e) {
dao.saveOrUpdate(e);
return e;
}
/**
*
* @param id
* @return
*/
public E findById(Integer id) {
return dao.findById(id);
}
/**
*
* @return
*/
public List<E> findAll() {
return dao.findAll();
}
/**
*
* @param e
*/
@Transactional(readOnly = false)
public void delete(E e) {
dao.delete(e);
}
}
| package de.terrestris.shogun2.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import de.terrestris.shogun2.model.PersistentObject;
/**
* This abstract service class provides basic CRUD functionality.
*
* @author Nils Bühner
* @see AbstractDaoService
*
*/
public abstract class AbstractCrudService<E extends PersistentObject> extends
AbstractDaoService<E> {
/**
*
* @param e
* @return
*/
@Transactional(readOnly = false)
public E saveOrUpdate(E e) {
dao.saveOrUpdate(e);
return e;
}
/**
*
* @param id
* @return
*/
public E findById(Integer id) {
return dao.findById(id);
}
/**
*
* @return
*/
public List<E> findAll() {
return dao.findAll();
}
/**
*
* @param e
*/
public void delete(E e) {
dao.delete(e);
}
}
|
Add dependency for the Search controller on the Listings component. | <?php
App::uses('AppController', 'Controller');
/**
* Search controller
*
* Handles site-wide search.
*/
class SearchController extends AppController
{
/**
* Controller name
*
* @var string
*/
public $name = 'Search';
/**
* The components this controller uses.
*
* @var array
*/
public $components = array(
'Products',
'Listings'
);
/**
* The models this controller uses.
*
* @var array
*/
public $uses = array('ProductListing');
public function this($description, $start = 0)
{
$products = $this->Products->searchSemantics3($description, $start);
$this->set('products', $products);
$productIds = array_map(function($item) {
return $item->id;
}, $products->results);
$listings = $this->ProductListing->findAllByProductId($productIds);
$this->Listings->augmentProductInfo($listings);
$this->Listings->sanitise($listings);
$this->set('listings', $listings);
$this->set('_serialize', array('products', 'listings'));
}
}
| <?php
App::uses('AppController', 'Controller');
/**
* Search controller
*
* Handles site-wide search.
*/
class SearchController extends AppController
{
/**
* Controller name
*
* @var string
*/
public $name = 'Search';
/**
* The components this controller uses.
*
* @var array
*/
public $components = array(
'Products'
);
/**
* The models this controller uses.
*
* @var array
*/
public $uses = array('ProductListing');
public function this($description, $start = 0)
{
$products = $this->Products->searchSemantics3($description, $start);
$this->set('products', $products);
$productIds = array_map(function($item) {
return $item->id;
}, $products->results);
$listings = $this->ProductListing->findAllByProductId($productIds);
$this->Listings->augmentProductInfo($listings);
$this->Listings->sanitise($listings);
$this->set('listings', $listings);
$this->set('_serialize', array('products', 'listings'));
}
}
|
Fix the admin url configuration. | # -*- coding: utf-8 -*-
# Copyright (C) 1998-2016 by the Free Software Foundation, Inc.
#
# This file is part of Postorius.
#
# Postorius is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# Postorius is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# Postorius. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import reverse_lazy
from django.views.generic import RedirectView
urlpatterns = [
url(r'^$', RedirectView.as_view(
url=reverse_lazy('list_index'),
permanent=True)),
url(r'^postorius/', include('postorius.urls')),
url(r'^hyperkitty/', include('hyperkitty.urls')),
url(r'', include('django_mailman3.urls')),
url(r'^accounts/', include('allauth.urls')),
# Django admin
url(r'^admin/', admin.site.urls),
]
| # -*- coding: utf-8 -*-
# Copyright (C) 1998-2016 by the Free Software Foundation, Inc.
#
# This file is part of Postorius.
#
# Postorius is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# Postorius is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# Postorius. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import reverse_lazy
from django.views.generic import RedirectView
urlpatterns = [
url(r'^$', RedirectView.as_view(
url=reverse_lazy('list_index'),
permanent=True)),
url(r'^postorius/', include('postorius.urls')),
url(r'^hyperkitty/', include('hyperkitty.urls')),
url(r'', include('django_mailman3.urls')),
url(r'^accounts/', include('allauth.urls')),
# Django admin
url(r'^admin/', include(admin.site.urls)),
]
|
Update test to use await. | import ghost from 'ghostjs'
import assert from 'assert'
import localServer from './fixtures/server.js'
describe('ghost#usePage', () => {
before(localServer)
after(localServer.stop)
it('we can switch pages using usePage()', async () => {
await ghost.open('http://localhost:8888/basic_content.html')
let myElement = await ghost.findElement('#popupLink')
await myElement.click()
await ghost.wait(5000)
await ghost.waitForPage('form.html')
// Switch to the popup context
await ghost.usePage('form.html')
// Find an element which is in the new page, but not the first.
let checkbox = await ghost.findElement('#checkbox1')
assert.equal(await checkbox.isVisible(), true)
// Switch back to the main page.
await ghost.usePage()
// The checkbox should not exist
let goAwayCheckbox = await ghost.findElement('#checkbox1')
assert.equal(goAwayCheckbox, null)
})
})
| import ghost from 'ghostjs'
import assert from 'assert'
import localServer from './fixtures/server.js'
describe('ghost#usePage', () => {
before(localServer)
after(localServer.stop)
it('we can switch pages using usePage()', async () => {
await ghost.open('http://localhost:8888/basic_content.html')
let myElement = await ghost.findElement('#popupLink')
await myElement.click()
await ghost.wait(5000)
await ghost.waitForPage('form.html')
// Switch to the popup context
ghost.usePage('form.html')
// Find an element which is in the new page, but not the first.
let checkbox = await ghost.findElement('#checkbox1')
assert.equal(await checkbox.isVisible(), true)
// Switch back to the main page.
ghost.usePage()
// The checkbox should not exist
let goAwayCheckbox = await ghost.findElement('#checkbox1')
assert.equal(goAwayCheckbox, null)
})
})
|
Fix smooth scrolling breaking new navigation | function figure_downloads() {
var figs = $("div[id^=F]");
$( figs ).each( function( index, element ){
$(this).find('.fig-caption').prepend('<p class="fig-download"><i class="fa fa-download"> </i><a target="_blank" href="' + $( this ).find('img').attr('src') +'">Download</a></p>' );
});
}
function table_downloads() {
var tables = $("div[id^=T]");
console.log(tables);
$( tables ).each( function( index, element ){
console.log(this);
$(this).find('.table-caption').prepend('<p class="fig-download"><i class="fa fa-download"> </i><a target="_blank" href="table/' + $( this ).attr('id') +'">Download</a></p>' );
});
}
$( document ).ready(function(){
$(".button-collapse").sideNav();
$('select').material_select();
$('.modal').modal();
figure_downloads();
table_downloads();
})
var $root = $('html, body');
$('a[href^="#"]').click(function() {
var href = $.attr(this, 'href');
if (href && href != "#!") {
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
}
return false;
});
| function figure_downloads() {
var figs = $("div[id^=F]");
$( figs ).each( function( index, element ){
$(this).find('.fig-caption').prepend('<p class="fig-download"><i class="fa fa-download"> </i><a target="_blank" href="' + $( this ).find('img').attr('src') +'">Download</a></p>' );
});
}
function table_downloads() {
var tables = $("div[id^=T]");
console.log(tables);
$( tables ).each( function( index, element ){
console.log(this);
$(this).find('.table-caption').prepend('<p class="fig-download"><i class="fa fa-download"> </i><a target="_blank" href="table/' + $( this ).attr('id') +'">Download</a></p>' );
});
}
$( document ).ready(function(){
$(".button-collapse").sideNav();
$('select').material_select();
$('.modal').modal();
figure_downloads();
table_downloads();
})
var $root = $('html, body');
$('a[href^="#"]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});
|
Add a different color for scatter plots to differentiate from line. | """
This module serves as an interface to
matplotlib.
"""
from utils import config
OFFSET = 2 # offset = max_x/stepsize * OFFSET
def init(output):
import matplotlib
config.mpl(matplotlib, bool(output))
from matplotlib import pyplot
globals()['plt'] = pyplot
def line_plot(xs, ys, color='red'):
plt.plot(
xs,
ys,
color=color,
linewidth=2.0
)
def legend(*args):
plt.legend(args, loc='best')
def scatter_plot(x, y, color='blue'):
plt.scatter(x, y, color=color)
def scale_plot(max_x, stepsize):
offset = max_x/stepsize * OFFSET
plt.axis(xmin=-offset, xmax=max_x+offset, ymin=0)
def prepare_plot(xlabel, ylabel, title):
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.grid(True)
def display_plot(output):
if output:
if output == 'stdout':
plt.savefig(sys.stdout, format='png')
else:
plt.savefig(output)
else:
plt.show()
| """
This module serves as an interface to
matplotlib.
"""
from utils import config
OFFSET = 2 # offset = max_x/stepsize * OFFSET
def init(output):
import matplotlib
config.mpl(matplotlib, bool(output))
from matplotlib import pyplot
globals()['plt'] = pyplot
def line_plot(xs, ys, color='red'):
plt.plot(
xs,
ys,
color=color,
linewidth=2.0
)
def legend(*args):
plt.legend(args, loc='best')
def scatter_plot(x, y, color='red'):
plt.scatter(x, y, color=color)
def scale_plot(max_x, stepsize):
offset = max_x/stepsize * OFFSET
plt.axis(xmin=-offset, xmax=max_x+offset, ymin=0)
def prepare_plot(xlabel, ylabel, title):
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.grid(True)
def display_plot(output):
if output:
if output == 'stdout':
plt.savefig(sys.stdout, format='png')
else:
plt.savefig(output)
else:
plt.show()
|
Fix syntax error for PHP 5.3 | <?php
namespace Concise\Services;
class TimeFormatter
{
protected function pluralize($number, $word)
{
return "{$number} {$word}" . (($number == 1) ? '' : 's');
}
protected function part(array &$r, &$seconds, $size, $word)
{
if ($seconds >= $size) {
$x = floor($seconds / $size);
$r[] = $this->pluralize($x, $word);
$seconds -= $x * $size;
}
}
public function format($seconds)
{
if (0 == $seconds) {
return '0 seconds';
}
$r = array();
$this->part($r, $seconds, 3600, 'hour');
$this->part($r, $seconds, 60, 'minute');
$this->part($r, $seconds, 1, 'second');
return implode(' ', $r);
}
}
| <?php
namespace Concise\Services;
class TimeFormatter
{
protected function pluralize($number, $word)
{
return "{$number} {$word}" . (($number == 1) ? '' : 's');
}
protected function part(array &$r, &$seconds, $size, $word)
{
if ($seconds >= $size) {
$x = floor($seconds / $size);
$r[] = $this->pluralize($x, $word);
$seconds -= $x * $size;
}
}
public function format($seconds)
{
if (0 == $seconds) {
return '0 seconds';
}
$r = [];
$this->part($r, $seconds, 3600, 'hour');
$this->part($r, $seconds, 60, 'minute');
$this->part($r, $seconds, 1, 'second');
return implode(' ', $r);
}
}
|
Fix getting host ip on linux | import asyncio
import os
import logging
import re
import dns.resolver
logging.basicConfig()
from .server import HTTPServer
from .mapper import update_config, add_container
logger = logging.getLogger('small-prox')
def _get_local_address():
resolver = dns.resolver.Resolver()
try:
resolver.query('docker.for.mac.localhost')
return 'docker.for.mac.localhost'
except:
# must be on linux, get host ip
result = os.popen('ip r').read()
ip = re.match('default via (.*?)\s', result).groups(1)[0]
return ip
def main():
config = {}
if os.getenv('DEBUG') == 'true':
logger.setLevel('DEBUG')
loop = asyncio.get_event_loop()
local_ports = os.getenv('LOCAL_PORTS', [])
local_ports = local_ports and local_ports.split(',')
local_address = _get_local_address()
for port in local_ports:
add_container(None, port, config, ip=local_address)
logger.debug('Current container map: %s', config)
server = HTTPServer(loop, config)
loop.run_until_complete(server.start())
loop.create_task(update_config(config))
loop.run_forever()
| import asyncio
import os
import logging
import re
import dns.resolver
logging.basicConfig()
from .server import HTTPServer
from .mapper import update_config, add_container
logger = logging.getLogger('small-prox')
def _get_local_address():
resolver = dns.resolver.Resolver()
try:
resolver.query('docker.for.mac.localhost')
return 'docker.for.mac.localhost'
except:
# must be on linux, get host ip
result = os.popen('ip r').read()
ip, _ = re.match('default via (.*?)\s', result).groups(1)
return ip
def main():
config = {}
if os.getenv('DEBUG') == 'true':
logger.setLevel('DEBUG')
loop = asyncio.get_event_loop()
local_ports = os.getenv('LOCAL_PORTS', [])
local_ports = local_ports and local_ports.split(',')
local_address = _get_local_address()
for port in local_ports:
add_container(None, port, config, ip=local_address)
logger.debug('Current container map: %s', config)
server = HTTPServer(loop, config)
loop.run_until_complete(server.start())
loop.create_task(update_config(config))
loop.run_forever()
|
Substitute Date annotation with Field(type="date") | <?php
namespace Gedmo\SoftDeleteable\Traits;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* SoftDeletable Trait, usable with PHP >= 5.4
*
* @author Wesley van Opdorp <wesley.van.opdorp@freshheads.com>
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
trait SoftDeleteableDocument
{
/**
* @var \DateTime
* @ODM\Field(type="date")
*/
protected $deletedAt;
/**
* Sets deletedAt.
*
* @param \Datetime|null $deletedAt
*
* @return $this
*/
public function setDeletedAt(\DateTime $deletedAt = null)
{
$this->deletedAt = $deletedAt;
return $this;
}
/**
* Returns deletedAt.
*
* @return \DateTime
*/
public function getDeletedAt()
{
return $this->deletedAt;
}
/**
* Is deleted?
*
* @return bool
*/
public function isDeleted()
{
return null !== $this->deletedAt;
}
}
| <?php
namespace Gedmo\SoftDeleteable\Traits;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
/**
* SoftDeletable Trait, usable with PHP >= 5.4
*
* @author Wesley van Opdorp <wesley.van.opdorp@freshheads.com>
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
trait SoftDeleteableDocument
{
/**
* @var \DateTime
* @ODM\Date
*/
protected $deletedAt;
/**
* Sets deletedAt.
*
* @param \Datetime|null $deletedAt
*
* @return $this
*/
public function setDeletedAt(\DateTime $deletedAt = null)
{
$this->deletedAt = $deletedAt;
return $this;
}
/**
* Returns deletedAt.
*
* @return \DateTime
*/
public function getDeletedAt()
{
return $this->deletedAt;
}
/**
* Is deleted?
*
* @return bool
*/
public function isDeleted()
{
return null !== $this->deletedAt;
}
}
|
Make Fabric honor .ssh/config settings | # -*- coding: utf-8 -*-
from contextlib import nested
from fabric.api import *
def prepare_project():
u"""
Enters the directory and sources environment configuration.
I know ``nested`` is deprecated, but what a nice shortcut it is here ;)
"""
return nested(
cd(PROJECT_PATH),
prefix("source ../.virtualenvs/variablestars3/bin/activate")
)
PROJECT_PATH = "$HOME/variablestars.net"
env.roledefs = {
'web': ["variablestars2@variablestars.net"],
}
env.color = True
env.forward_agent = True
env.use_ssh_config = True
@task
@roles("web")
def git_pull():
with cd(PROJECT_PATH):
run("git pull origin master")
@task
@roles("web")
def update_requirements():
with prepare_project():
run("pip install -r requirements.txt")
run("source ~/.nvm/nvm.sh && npm install")
@task
@roles("web")
def migrate():
with prepare_project():
run("python manage.py syncdb")
run("python manage.py migrate")
@task
@roles("web")
def collect_static():
with prepare_project():
run("python manage.py collectstatic --noinput")
@task
@roles("web")
def restart():
run("appctl restart variablestars2")
@task
@roles("web")
def deploy():
git_pull()
update_requirements()
migrate()
collect_static()
restart()
| # -*- coding: utf-8 -*-
from contextlib import nested
from fabric.api import *
def prepare_project():
u"""
Enters the directory and sources environment configuration.
I know ``nested`` is deprecated, but what a nice shortcut it is here ;)
"""
return nested(
cd(PROJECT_PATH),
prefix("source ../.virtualenvs/variablestars3/bin/activate")
)
PROJECT_PATH = "$HOME/variablestars.net"
env.roledefs = {
'web': ["variablestars2@variablestars.net"],
}
env.color = True
env.forward_agent = True
@task
@roles("web")
def git_pull():
with cd(PROJECT_PATH):
run("git pull origin master")
@task
@roles("web")
def update_requirements():
with prepare_project():
run("pip install -r requirements.txt")
run("source ~/.nvm/nvm.sh && npm install")
@task
@roles("web")
def migrate():
with prepare_project():
run("python manage.py syncdb")
run("python manage.py migrate")
@task
@roles("web")
def collect_static():
with prepare_project():
run("python manage.py collectstatic --noinput")
@task
@roles("web")
def restart():
run("appctl restart variablestars2")
@task
@roles("web")
def deploy():
git_pull()
update_requirements()
migrate()
collect_static()
restart()
|
Save the object itself, rather than a list of arguments | // node modules
import fs from 'fs';
// npm modules
import homedir from 'homedir';
const configFilePath = `${homedir()}/.urcli/config.json`;
export class Config {
constructor() {
try {
const config = JSON.parse(fs.readFileSync(configFilePath));
Object.assign(this, config);
} catch (e) {
// We can ignore ENOENT and throw on everything else.
if (e.code !== 'ENOENT') {
console.error('Error reading from filesystem.');
throw new Error(e);
}
}
}
save() {
const newConfigs = JSON.stringify(this, null, 2);
try {
fs.writeFileSync(configFilePath, newConfigs);
} catch (e) {
// We can create both the config folder and file on ENOENT and throw on
// everything else.
if (e.code !== 'ENOENT') {
console.error('Error while saving the config file.');
throw new Error(e);
}
fs.mkdirSync(`${homedir()}/.urcli`);
fs.writeFileSync(configFilePath, newConfigs);
}
return this;
}
}
| // node modules
import fs from 'fs';
// npm modules
import homedir from 'homedir';
const configFilePath = `${homedir()}/.urcli/config.json`;
export class Config {
constructor() {
try {
const config = JSON.parse(fs.readFileSync(configFilePath));
Object.assign(this, config);
} catch (e) {
// We can ignore ENOENT and throw on everything else.
if (e.code !== 'ENOENT') {
console.error('Error reading from filesystem.');
throw new Error(e);
}
}
}
save(configValues) {
Object.assign(this, configValues);
const config = JSON.stringify(this, null, 2);
try {
fs.writeFileSync(configFilePath, config);
} catch (e) {
// We can create both the config folder and file on ENOENT and throw on
// everything else.
if (e.code !== 'ENOENT') {
console.error('Error while saving the config file.');
throw new Error(e);
}
fs.mkdirSync(`${homedir()}/.urcli`);
fs.writeFileSync(configFilePath, config);
}
return this;
}
}
|
Add link for creating new animal. | @extends('layouts.app')
@section('content')
<a href="{{ action('AnimalController@create') }}">{{ __('Add animal') }}</a>
@if(count($animals) == 0)
{{ __('There are no animals.') }}
@else
<table class="table table-responsive table-bordered">
<tr>
<th>{{ __('Name') }}</th>
<th>{{ __('Dob') }}</th>
<th>{{ __('Own') }}</th>
<th>{{ __('Active') }}</th>
<th>{{ __('Options') }}</th>
</tr>
@each('animal.index.item', $animals, 'animal')
</table>
{{$animals->links()}}
@endif
@stop | @extends('layouts.app')
@section('content')
@if(count($animals) == 0)
{{__('There are no animals.')}}
@else
<table class="table table-responsive table-bordered">
<tr>
<th>{{__('Name')}}</th>
<th>{{__('Dob')}}</th>
<th>{{__('Own')}}</th>
<th>{{__('Active')}}</th>
<th>{{__('Options')}}</th>
</tr>
@each('animal.index.item', $animals, 'animal')
</table>
{{$animals->links()}}
@endif
@stop |
Set treePaths instead of `treeFor`. | 'use strict';
module.exports = {
name: 'Ember CLI ic-ajax',
init: function(name) {
this.treePaths['vendor'] = 'node_modules';
},
included: function(app) {
var options = this.app.options.icAjaxOptions || {enabled: true};
if (options.enabled) {
this.app.import('vendor/ic-ajax/dist/named-amd/main.js', {
exports: {
'ic-ajax': [
'default',
'defineFixture',
'lookupFixture',
'raw',
'request',
]
}
});
}
}
};
| 'use strict';
module.exports = {
name: 'Ember CLI ic-ajax',
treeFor: function(name) {
if (name !== 'vendor') { return; }
return this.treeGenerator(path.join(__dirname, 'node_modules'));
},
included: function(app) {
this._super.included(app);
var options = this.app.options.icAjaxOptions || {enabled: true};
if (options.enabled) {
this.app.import('vendor/ic-ajax/dist/named-amd/main.js', {
exports: {
'ic-ajax': [
'default',
'defineFixture',
'lookupFixture',
'raw',
'request',
]
}
});
}
}
};
|
Add protection against accidents in tests | // auth0 rules rely on a configuration object, which is a set of secrets stored inside auth0, so we need to
// hoist them. Mozilla-IAM also uses a "global" object that is normally at the top of the rules list, and is
// contained inside global.js, which is a pruned down copy of Global-Function-Declarations.js
const fs = require('fs');
const path = require('path');
const requireFromString = require('require-from-string');
module.exports = {
// no idea from the docs what the first variable is
handler: (_ = null, user, context) => {
return {
context,
user,
}
},
load: (filename, preExportEval = '', silent = true) => {
const ruleFile = path.join(__dirname, '../../rules', `${filename}`);
// this is here because you can easily screw up your tests if you
// switch the order of preExportEval and silent
if (typeof silent !== 'boolean') {
throw 'Incorrect argument order in rule loader';
}
const silence = silent ? `console.log = console.error = () => {};` : '';
// shim auth0 globals into each rule, and set each function to be the global export
const ruleText = `
const configuration = require('./modules/global/configuration.js');
const global = require('./modules/global/global.js');
${silence}
${preExportEval}
module.exports = ${fs.readFileSync(ruleFile, 'utf8')};
`;
const ruleModule = requireFromString(ruleText, filename);
return ruleModule;
}
};
| // auth0 rules rely on a configuration object, which is a set of secrets stored inside auth0, so we need to
// hoist them. Mozilla-IAM also uses a "global" object that is normally at the top of the rules list, and is
// contained inside global.js, which is a pruned down copy of Global-Function-Declarations.js
const fs = require('fs');
const path = require('path');
const requireFromString = require('require-from-string');
module.exports = {
// no idea from the docs what the first variable is
handler: (_ = null, user, context) => {
return {
context,
user,
}
},
load: (filename, preExportEval = '', silent = true) => {
const ruleFile = path.join(__dirname, '../../rules', `${filename}`);
const silence = silent ? `console.log = console.error = () => {};` : '';
// shim auth0 globals into each rule, and set each function to be the global export
const ruleText = `
const configuration = require('./modules/global/configuration.js');
const global = require('./modules/global/global.js');
${silence}
${preExportEval}
module.exports = ${fs.readFileSync(ruleFile, 'utf8')};
`;
const ruleModule = requireFromString(ruleText, filename);
return ruleModule;
}
};
|
Add newline at the end of file | /*
Copyright 2018 Google LLC
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 cmd
import (
"io"
"os"
"github.com/spf13/cobra"
)
// completionCmd represents the completion command
var completionCmd = &cobra.Command{
Use: "completion",
Short: "Generate shell completion scripts",
Long: `To enable command completion run
eval "$(skaffold completion bash)"
To configure bash shell completion for all your sessions, add the following to your
~/.bashrc or ~/.bash_profile:
eval "$(skaffold completion bash)"`,
Run: func(cmd *cobra.Command, args []string) {
rootCmd.GenBashCompletion(os.Stdout);
},
}
func NewCmdCompletion(out io.Writer) *cobra.Command {
return completionCmd
}
| /*
Copyright 2018 Google LLC
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 cmd
import (
"io"
"os"
"github.com/spf13/cobra"
)
// completionCmd represents the completion command
var completionCmd = &cobra.Command{
Use: "completion",
Short: "Generate shell completion scripts",
Long: `To enable command completion run
eval "$(skaffold completion bash)"
To configure bash shell completion for all your sessions, add the following to your
~/.bashrc or ~/.bash_profile:
eval "$(skaffold completion bash)"`,
Run: func(cmd *cobra.Command, args []string) {
rootCmd.GenBashCompletion(os.Stdout);
},
}
func NewCmdCompletion(out io.Writer) *cobra.Command {
return completionCmd
} |
Fix a deprecation warning; content_type replaces mimetype | import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
cache_path = settings.WORDCLOUD_CACHE_PATH
if os.path.exists(cache_path):
response = HttpResponse()
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
content_type='application/json',
)
| import json
import os
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
cache_path = settings.WORDCLOUD_CACHE_PATH
if os.path.exists(cache_path):
response = HttpResponse()
response['Content-Type'] = 'application/json'
response['X-Sendfile'] = cache_path.encode('utf-8')
return response
content = json.dumps(popular_words(max_entries=max_entries))
return HttpResponse(
content,
mimetype='application/json',
)
|
Add google event tracking capability | import { GOOGLE_ANALYTICS_ID } from '../AppSettings';
import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge';
let tracker = new GoogleAnalyticsTracker(GOOGLE_ANALYTICS_ID);
/**
* A module containing logging helper functions
* @module util/logger
*/
module.exports = {
/**
* Send a log message to the console
* @function
* @param {string} msg The message to log
*/
log(msg) {
console.log(msg);
},
/**
* Sends a trackScreenView message to Google Analytics
* @function
* @param {string} msg The message to log
*/
ga(msg) {
tracker.trackScreenView(msg);
},
/**
* Sends a trackEvent message to Google Analytics
* @function
* @param {string} category The category of event
* @param {string} action The name of the action
*/
trackEvent(category, action) {
tracker.trackEvent(category, action);
},
/**
* Sends a trackException message to Google Analytics
* @function
* @param {string} error The error message
* @param {bool} fatal If the crash was fatal or not
*/
trackException(error, fatal) {
tracker.trackException(error, fatal);
},
};
| import { GOOGLE_ANALYTICS_ID } from '../AppSettings';
import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge';
let tracker = new GoogleAnalyticsTracker(GOOGLE_ANALYTICS_ID);
/**
* A module containing logging helper functions
* @module util/logger
*/
module.exports = {
/**
* Send a log message to the console
* @function
* @param {string} msg The message to log
*/
log(msg) {
console.log(msg);
},
/**
* Sends a trackScreenView message to Google Analytics
* @function
* @param {string} msg The message to log
*/
ga(msg) {
tracker.trackScreenView(msg);
},
/**
* Sends a trackException message to Google Analytics
* @function
* @param {string} error The error message
* @param {bool} fatal If the crash was fatal or not
*/
trackException(error, fatal) {
tracker.trackException(error, fatal);
},
};
|
Make the Amazon:S3:CopyObject example nicer | var fmt = require('fmt');
var awssum = require('awssum');
var amazon = awssum.load('amazon/amazon');
var S3 = awssum.load('amazon/s3').S3;
var env = process.env;
var accessKeyId = env.ACCESS_KEY_ID;
var secretAccessKey = env.SECRET_ACCESS_KEY;
var awsAccountId = env.AWS_ACCOUNT_ID;
var s3 = new S3({
'accessKeyId' : accessKeyId,
'secretAccessKey' : secretAccessKey,
'region' : amazon.US_EAST_1
});
fmt.line();
fmt.title('s3.CopyObject');
fmt.field('Region', s3.region() );
fmt.field('EndPoint', s3.host() );
fmt.field('AccessKeyId', s3.accessKeyId() );
fmt.field('SecretAccessKey', s3.secretAccessKey().substr(0, 3) + '...' );
fmt.field('AwsAccountId', s3.awsAccountId() );
fmt.line();
var options = {
BucketName : 'pie-18',
ObjectName : 'copy-of-test-object.txt',
SourceBucket : 'pie-18',
SourceObject : 'test-object.txt',
};
s3.CopyObject(options, function(err, data) {
fmt.msg("copying one object to another - expecting success");
fmt.dump(err, 'Error');
fmt.dump(data, 'Data');
fmt.line();
});
| var fmt = require('fmt');
var awssum = require('awssum');
var amazon = awssum.load('amazon/amazon');
var S3 = awssum.load('amazon/s3').S3;
var env = process.env;
var accessKeyId = env.ACCESS_KEY_ID;
var secretAccessKey = env.SECRET_ACCESS_KEY;
var awsAccountId = env.AWS_ACCOUNT_ID;
var s3 = new S3({
'accessKeyId' : accessKeyId,
'secretAccessKey' : secretAccessKey,
'region' : amazon.US_EAST_1
});
fmt.field('Region', s3.region() );
fmt.field('EndPoint', s3.host() );
fmt.field('AccessKeyId', s3.accessKeyId() );
fmt.field('SecretAccessKey', s3.secretAccessKey().substr(0, 3) + '...' );
fmt.field('AwsAccountId', s3.awsAccountId() );
var options = {
BucketName : 'pie-18',
ObjectName : 'copy-of-test-object.txt',
SourceBucket : 'pie-18',
SourceObject : 'test-object.txt',
};
s3.CopyObject(options, function(err, data) {
fmt.msg("copying one object to another - expecting success");
fmt.dump(err, 'Error');
fmt.dump(data, 'Data');
});
|
Test for when objects touch | collisions = TestCase("collisions");
collisions.prototype.testMiss = function() {
var miss = nitch.collision.AABB({
width: 200,
height: 100,
x: 30,
y: 50
}, {
width: 100,
height: 200,
x: 800,
y: 500
});
assertFalse(miss);
}
collisions.prototype.testCollide = function() {
var collide = nitch.collision.AABB({
width: 200,
height: 100,
x: 30,
y: 50
}, {
width: 100,
height: 200,
x: 25,
y: 40
});
assertObject(collide);
assertEquals('right', collide.dir);
assertArray(collide.pv);
assertEquals(95, collide.pv[0]);
assertEquals(-110, collide.pv[1]);
}
collisions.prototype.testTouching = function() {
var touch = nitch.collision.AABB({
width: 200,
height: 100,
x: 30,
y: 50
}, {
width: 200,
height: 100,
x: 230,
y: 150
});
assertObject(touch);
assertEquals('bottom', touch.dir);
assertArray(touch.pv);
assertEquals(0, touch.pv[0]);
assertEquals(0, touch.pv[1]);
}
| collisions = TestCase("collisions");
collisions.prototype.testMiss = function() {
var miss = nitch.collision.AABB({
width: 200,
height: 100,
x: 30,
y: 50
}, {
width: 100,
height: 200,
x: 800,
y: 500
});
assertFalse(miss);
}
collisions.prototype.testCollide = function() {
var collide = nitch.collision.AABB({
width: 200,
height: 100,
x: 30,
y: 50
}, {
width: 100,
height: 200,
x: 25,
y: 40
});
assertObject(collide);
assertEquals('right', collide.dir);
assertArray(collide.pv);
assertEquals(95, collide.pv[0]);
assertEquals(-110, collide.pv[1]);
}
|
Use stdout when stderr is empty | var exec = require('child_process').exec;
var through = require('through2');
var gutil = require('gulp-util');
var merge = require('merge');
var PluginError = gutil.PluginError;
var vnuJar = require('vnu-jar');
module.exports = function(opt) {
var vnuCmd = 'java -Xss512k -jar ' + vnuJar + ' ';
var options = merge({
'errors-only': false,
'format': 'gnu',
'html': false,
'no-stream': false,
'verbose': false,
}, opt);
// Set options
Object.keys(options).forEach(function (key) {
var val = options[key];
if (key === 'format' && val !== 'gnu') vnuCmd += '--format ' + val + ' ';
if (val === true) vnuCmd += '--' + key + ' ';
});
var stream = through.obj(function(file, enc, cb) {
if (file.isNull()) return cb(null, file);
if (file.isStream()) {
return cb(new PluginError('gulp-html', 'Streaming not supported'));
}
exec(vnuCmd + file.history, function (err, stdout, stderr) {
if (err === null) return cb(null, file);
return cb(new PluginError('gulp-html', stderr || stdout));
});
});
return stream;
};
| var exec = require('child_process').exec;
var through = require('through2');
var gutil = require('gulp-util');
var merge = require('merge');
var PluginError = gutil.PluginError;
var vnuJar = require('vnu-jar');
module.exports = function(opt) {
var vnuCmd = 'java -Xss512k -jar ' + vnuJar + ' ';
var options = merge({
'errors-only': false,
'format': 'gnu',
'html': false,
'no-stream': false,
'verbose': false,
}, opt);
// Set options
Object.keys(options).forEach(function (key) {
var val = options[key];
if (key === 'format' && val !== 'gnu') vnuCmd += '--format ' + val + ' ';
if (val === true) vnuCmd += '--' + key + ' ';
});
var stream = through.obj(function(file, enc, cb) {
if (file.isNull()) return cb(null, file);
if (file.isStream()) {
return cb(new PluginError('gulp-html', 'Streaming not supported'));
}
exec(vnuCmd + file.history, function (err, stdout, stderr) {
if (err === null) return cb(null, file);
return cb(new PluginError('gulp-html', stderr));
});
});
return stream;
};
|
Update invalidate to remove failed trials. | #!/usr/bin/env python3
# Copyright (c) 2017, John Skinner
import sys
import logging
import logging.config
import config.global_configuration as global_conf
import database.client
import batch_analysis.invalidate
def main():
"""
Run a particular task.
:args: Only argument is the id of the task to run
:return:
"""
config = global_conf.load_global_config('config.yml')
if __name__ == '__main__':
# Only configure the logging if this is the main function, don't reconfigure
logging.config.dictConfig(config['logging'])
db_client = database.client.DatabaseClient(config=config)
orbslam_ids = db_client.system_collection.find({'_type': 'systems.slam.orbslam2.ORBSLAM2'}, {'_id': True})
for system_id in orbslam_ids:
logging.getLogger(__name__).info("Invalidating system {0}".format(system_id['_id']))
batch_analysis.invalidate.invalidate_system(db_client, system_id['_id'])
failed_trials = db_client.trials_collection.find({'success': False}, {'_id': True})
for trial_id in failed_trials:
logging.getLogger(__name__).info("Invalidating failed trial {0}".format(trial_id['_id']))
batch_analysis.invalidate.invalidate_trial_result(db_client, trial_id['_id'])
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
# Copyright (c) 2017, John Skinner
import sys
import logging
import logging.config
import config.global_configuration as global_conf
import database.client
import batch_analysis.invalidate
def main():
"""
Run a particular task.
:args: Only argument is the id of the task to run
:return:
"""
config = global_conf.load_global_config('config.yml')
if __name__ == '__main__':
# Only configure the logging if this is the main function, don't reconfigure
logging.config.dictConfig(config['logging'])
db_client = database.client.DatabaseClient(config=config)
orbslam_ids = db_client.system_collection.find({'_type': 'systems.slam.orbslam2.ORBSLAM2'}, {'_id': True})
for system_id in orbslam_ids:
logging.getLogger(__name__).info("Invalidating system {0}".format(system_id['_id']))
batch_analysis.invalidate.invalidate_system(db_client, system_id['_id'])
if __name__ == '__main__':
main()
|
Declare sum variable in test with truth (assertion library) | /*
* (C) Copyright 2020 Boni Garcia (http://bonigarcia.github.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.github.bonigarcia;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
public class TruthTest {
final Logger log = getLogger(lookup().lookupClass());
@Test
void test() {
log.debug("Assertion using Truth");
int sum = 1 + 1;
assertThat(sum).isEqualTo(2);
}
}
| /*
* (C) Copyright 2020 Boni Garcia (http://bonigarcia.github.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.github.bonigarcia;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
public class TruthTest {
final Logger log = getLogger(lookup().lookupClass());
@Test
void test() {
log.debug("Assertion using Truth");
assertThat(1 + 1).isEqualTo(2);
}
}
|
Revert sales invoice dn link issue | from frappe import _
def get_data():
return {
'fieldname': 'sales_invoice',
'non_standard_fieldnames': {
'Delivery Note': 'against_sales_invoice',
'Journal Entry': 'reference_name',
'Payment Entry': 'reference_name',
'Payment Request': 'reference_name',
'Sales Invoice': 'return_against'
},
'internal_links': {
'Sales Order': ['items', 'sales_order']
},
'transactions': [
{
'label': _('Payment'),
'items': ['Payment Entry', 'Payment Request', 'Journal Entry']
},
{
'label': _('Reference'),
'items': ['Timesheet', 'Delivery Note', 'Sales Order']
},
{
'label': _('Returns'),
'items': ['Sales Invoice']
},
]
} | from frappe import _
def get_data():
return {
'fieldname': 'sales_invoice',
'non_standard_fieldnames': {
'Delivery Note': 'against_sales_invoice',
'Journal Entry': 'reference_name',
'Payment Entry': 'reference_name',
'Payment Request': 'reference_name',
'Sales Invoice': 'return_against'
},
'internal_links': {
'Sales Order': ['items', 'sales_order'],
'Delivery Note': ['items', 'delivery_note']
},
'transactions': [
{
'label': _('Payment'),
'items': ['Payment Entry', 'Payment Request', 'Journal Entry']
},
{
'label': _('Reference'),
'items': ['Timesheet', 'Delivery Note', 'Sales Order']
},
{
'label': _('Returns'),
'items': ['Sales Invoice']
},
]
} |
Add karma bot to inline data whitelist | <?php
namespace App\Middlewares;
use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;
/**
* Class InlineDataMiddleware
* @package App\Gitter\Middleware
*/
class InlineDataMiddleware implements MiddlewareInterface
{
/**
* @param Message $message
* @return mixed
*/
public function handle(Message $message)
{
$isImage = preg_match(
sprintf('/([^`]%s|^%1$s)/iu', 'http(?:s)?:\/\/.*?\.(?:jpg|png|jpeg|svg|bmp|gif)')
, $message->text);
$isVideo = preg_match(
sprintf('/([^`]%s|^%1$s)/iu', 'http(?:s)?:\/\/(?:www\.)?(?:youtube\.com|youtu\.be)')
, $message->text);
if (($isImage || $isVideo) && $message->user->login !== \Auth::user()->login) {
// Move to lang files
$answer = sprintf('@%s, просьба оборачивать в кавычки ссылки на видео и изображения.', $message->user->login);
$message->italic($answer);
}
return $message;
}
}
| <?php
namespace App\Middlewares;
use App\Message;
use App\Gitter\Middleware\MiddlewareInterface;
/**
* Class InlineDataMiddleware
* @package App\Gitter\Middleware
*/
class InlineDataMiddleware implements MiddlewareInterface
{
/**
* @param Message $message
* @return mixed
*/
public function handle(Message $message)
{
$isImage = preg_match(
sprintf('/([^`]%s|^%1$s)/iu', 'http(?:s)?:\/\/.*?\.(?:jpg|png|jpeg|svg|bmp|gif)')
, $message->text);
$isVideo = preg_match(
sprintf('/([^`]%s|^%1$s)/iu', 'http(?:s)?:\/\/(?:www\.)?(?:youtube\.com|youtu\.be)')
, $message->text);
if ($isImage || $isVideo) {
// Move to lang files
$answer = sprintf('@%s, просьба оборачивать в кавычки ссылки на видео и изображения.', $message->user->login);
$message->italic($answer);
}
return $message;
}
}
|
Remove kube and add react touch events | require('./lib/whatwg-fetch/fetch.js')
//require('./lib/kube-6.0.1/kube.min.css')
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import 'react-hot-loader/patch'
import React from 'react'
import ReactDOM from 'react-dom'
import Root from './components/Root'
import configureStore from './configureStore'
const store = configureStore()
// import { AppContainer } from 'react-hot-loader'
ReactDOM.render(
<Root store={ store } />,
document.getElementById('app')
)
// if (module.hot) {
// module.hot.accept('./containers/CashmereAppContainer', () => {
// const NextCashmereAppContainer = require('./containers/CashmereAppContainer').CashmereAppContainer
// ReactDOM.render(
// // <AppContainer>
// <Provider store={ store }>
// <NextCashmereAppContainer />
// </Provider>,
// // </AppContainer>,
// rootEl
// )
// })
// }
| require('./lib/whatwg-fetch/fetch.js')
require('./lib/kube-6.0.1/kube.min.css')
import 'react-hot-loader/patch'
import React from 'react'
import ReactDOM from 'react-dom'
import Root from './components/Root'
import configureStore from './configureStore'
const store = configureStore()
// import { AppContainer } from 'react-hot-loader'
ReactDOM.render(
<Root store={ store } />,
document.getElementById('app')
)
// if (module.hot) {
// module.hot.accept('./containers/CashmereAppContainer', () => {
// const NextCashmereAppContainer = require('./containers/CashmereAppContainer').CashmereAppContainer
// ReactDOM.render(
// // <AppContainer>
// <Provider store={ store }>
// <NextCashmereAppContainer />
// </Provider>,
// // </AppContainer>,
// rootEl
// )
// })
// }
|
Update to expand exception string | # -*- coding: utf-8 -*-
# TM1py Exceptions are defined here
class TM1pyException(Exception):
""" The default exception for TM1py
"""
def __init__(self, response, status_code, reason, headers):
self._response = response
self._status_code = status_code
self._reason = reason
self._headers = headers
@property
def status_code(self):
return self._status_code
@property
def reason(self):
return self.reason
@property
def response(self):
return self._response
@property
def headers(self):
return self._headers
def __str__(self):
return "Text: {} Status Code: {} Reason: {} Headers {}".format(self._response,
self._status_code,
self._reason,
self._headers)
| # -*- coding: utf-8 -*-
# TM1py Exceptions are defined here
class TM1pyException(Exception):
""" The default exception for TM1py
"""
def __init__(self, response, status_code, reason, headers):
self._response = response
self._status_code = status_code
self._reason = reason
self._headers = headers
@property
def status_code(self):
return self._status_code
@property
def reason(self):
return self.reason
@property
def response(self):
return self._response
@property
def headers(self):
return self._headers
def __str__(self):
return "Text: {} Status Code: {} Reason: {}".format(self._response, self._status_code, self._reason)
|
Structure of a basic REST API | package main
import (
"fmt"
"log"
"net/http"
)
type article struct {
title string
datePosted int
desc string
content string
}
func homePage(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "Welcome to the HomePage!")
fmt.Println("Endpoint Hit: homePage")
}
func returnArticle(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "returns a specific article")
fmt.Println("Endpoint Hit: returnArticle")
}
func returnAllArticles(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "All Articles")
fmt.Println("Endpoint Hit: returnAllArticles")
}
func addArticle(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "Adds an article to list of articles")
fmt.Println("Endpoint Hit: addArticle")
}
func delArticle(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "deletes a specific article")
fmt.Println("Endpoint Hit: delArticle")
}
func handleRequests() {
http.HandleFunc("/", homePage)
http.HandleFunc("/all", returnAllArticles)
http.HandleFunc("/single", returnArticle)
http.HandleFunc("/delete", delArticle)
http.HandleFunc("/add", addArticle)
log.Fatal(http.ListenAndServe(":8081", nil))
}
func main() {
handleRequests()
} | package main
import (
"fmt"
"html"
"log"
"net/http"
)
type item struct {
node string
value int
}
type Node struct {
head item
left item
right item
}
func split(x int) (a, b, c int){
a = 1
b = 2
c = 3
return
}
func getChildren(a Node) (b, c item) {
b = a.left
c = a.right
return
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "Hi")
})
log.Fatal(http.ListenAndServe(":8081", nil))
} |
Fix expression: brace is missed | package com.intellij.debugger.streams.trace.smart.handler;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public class HashMapVariableImpl extends VariableImpl {
private final String myFromType;
public HashMapVariableImpl(@NotNull String name, @NotNull String from, @NotNull String to, boolean isLinked) {
super(String.format("Map<%s, %s>", from, to), name, isLinked ? "new LinkedHashMap<>()" : "new HashMap<>()");
myFromType = from;
}
public String convertToArray(@NotNull String arrayName) {
final StringBuilder builder = new StringBuilder();
final String newLine = System.lineSeparator();
builder.append("final ").append(arrayName).append(String.format(" = new Object[%s.size()];", getName())).append(System.lineSeparator());
builder.append("{").append(newLine);
builder.append("int i = 0;").append(newLine);
builder.append("for (final ").append(myFromType).append(String.format(" key : %s.keySet()) {", getName())).append(newLine);
builder.append("final Object value = ").append(String.format("%s.get(key);", getName())).append(newLine);
builder.append(String.format("%s[i] = ", arrayName)).append("new Object[] { key, value };").append(newLine);
builder.append(" }").append(newLine);
builder.append("}").append(newLine);
return builder.toString();
}
}
| package com.intellij.debugger.streams.trace.smart.handler;
import org.jetbrains.annotations.NotNull;
/**
* @author Vitaliy.Bibaev
*/
public class HashMapVariableImpl extends VariableImpl {
private final String myFromType;
public HashMapVariableImpl(@NotNull String name, @NotNull String from, @NotNull String to, boolean isLinked) {
super(String.format("Map<%s, %s>", from, to), name, isLinked ? "new LinkedHashMap<>()" : "new HashMap<>()");
myFromType = from;
}
public String convertToArray(@NotNull String arrayName) {
final StringBuilder builder = new StringBuilder();
final String newLine = System.lineSeparator();
builder.append("final ").append(arrayName).append(String.format("new Object[%s.size()];", getName())).append(System.lineSeparator());
builder.append("{").append(newLine);
builder.append("int i = 0;").append(newLine);
builder.append("for (final ").append(myFromType).append(String.format(" key : %s.keySet()) {", getName())).append(newLine);
builder.append("final Object value = ").append(String.format("%s.get(key);", getName())).append(newLine);
builder.append(String.format("%s[i] = ", arrayName)).append("new Object[] { key, value };").append(newLine);
builder.append("}").append(newLine);
return builder.toString();
}
}
|
Add a new line for each line of user input. | /**
* @author David Manouchehri
* Created on 6/17/15 at 6:56 PM.
* All content is under the MIT License unless otherwise specified.
* See LICENSE.txt for details.
*/
import java.util.Scanner;
public class ExpectedSalary {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
final int baseBSc = 28000;
final int expBSc = 6000;
final int baseMSc = 35000;
final int expMSc = 5000;
final int basePhD = 45000;
final int expPhD = 15000;
String degrees[] = {"BSc", "MSc", "PhD"};
/* Collect all the user input. */
String userInputs = "";
for(; userInput.hasNext();) {
String input = userInput.next();
if(input.equalsIgnoreCase("done"))
break;
userInputs += input + "\n";
}
Scanner scanner = new Scanner(userInputs);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}
| /**
* @author David Manouchehri
* Created on 6/17/15 at 6:56 PM.
* All content is under the MIT License unless otherwise specified.
* See LICENSE.txt for details.
*/
import java.util.Scanner;
public class ExpectedSalary {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
final int baseBSc = 28000;
final int expBSc = 6000;
final int baseMSc = 35000;
final int expMSc = 5000;
final int basePhD = 45000;
final int expPhD = 15000;
String degrees[] = {"BSc", "MSc", "PhD"};
/* Collect all the user input. */
String userInputs = "";
for(; userInput.hasNext();) {
String input = userInput.next();
if(input.equalsIgnoreCase("done"))
break;
userInputs += input;
}
Scanner scanner = new Scanner(userInputs);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}
|
Change page name to ConfigInterWikiLinks. | package net.hillsdon.svnwiki.configuration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import net.hillsdon.svnwiki.vc.PageInfo;
import net.hillsdon.svnwiki.vc.PageStore;
import net.hillsdon.svnwiki.vc.PageStoreException;
public class PageStoreConfiguration implements Configuration {
private final PageStore _store;
public PageStoreConfiguration(final PageStore store) {
_store = store;
}
public InterWikiLinker getInterWikiLinker() throws PageStoreException {
PageInfo page = _store.get("ConfigInterWikiLinks", -1);
InterWikiLinker linker = new InterWikiLinker();
if (!page.isNew()) {
parseLinkEntries(linker, page.getContent());
}
return linker;
}
private void parseLinkEntries(final InterWikiLinker linker, final String data) {
try {
BufferedReader reader = new BufferedReader(new StringReader(data));
String line;
while ((line = reader.readLine()) != null) {
int spaceIndex = line.indexOf(' ');
if (spaceIndex != -1) {
String wikiName = line.substring(0, spaceIndex).trim();
String formatString = line.substring(spaceIndex + 1).trim();
linker.addWiki(wikiName, formatString);
}
}
}
catch (IOException ex) {
throw new RuntimeException("I/O error reading from memory!", ex);
}
}
}
| package net.hillsdon.svnwiki.configuration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import net.hillsdon.svnwiki.vc.PageInfo;
import net.hillsdon.svnwiki.vc.PageStore;
import net.hillsdon.svnwiki.vc.PageStoreException;
public class PageStoreConfiguration implements Configuration {
private final PageStore _store;
public PageStoreConfiguration(final PageStore store) {
_store = store;
}
public InterWikiLinker getInterWikiLinker() throws PageStoreException {
PageInfo page = _store.get("InterWikiLinks", -1);
InterWikiLinker linker = new InterWikiLinker();
if (!page.isNew()) {
parseLinkEntries(linker, page.getContent());
}
return linker;
}
private void parseLinkEntries(final InterWikiLinker linker, final String data) {
try {
BufferedReader reader = new BufferedReader(new StringReader(data));
String line;
while ((line = reader.readLine()) != null) {
int spaceIndex = line.indexOf(' ');
if (spaceIndex != -1) {
String wikiName = line.substring(0, spaceIndex).trim();
String formatString = line.substring(spaceIndex + 1).trim();
linker.addWiki(wikiName, formatString);
}
}
}
catch (IOException ex) {
throw new RuntimeException("I/O error reading from memory!", ex);
}
}
}
|
Add a timestamp field to the Message model
The timestamp is automatically assigned at the moment of creation
of the message. It is represented as a Month-based ISO8601
date-time format when sending the Message resource representation
in JSON.
Closes #1 | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Member(models.Model):
lrz_id = models.CharField(max_length=7, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
def __str__(self):
return self.lrz_id
@python_2_unicode_compatible
class ChatRoom(models.Model):
name = models.CharField(max_length=100, unique=True)
members = models.ManyToManyField(Member, related_name='chat_rooms')
def __str__(self):
return self.name
@python_2_unicode_compatible
class Message(models.Model):
text = models.TextField()
member = models.ForeignKey(Member, related_name='messages')
chat_room = models.ForeignKey(ChatRoom, related_name='messages')
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{text} ({member})'.format(
text=self.text,
member=self.member
)
| from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Member(models.Model):
lrz_id = models.CharField(max_length=7, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
def __str__(self):
return self.lrz_id
@python_2_unicode_compatible
class ChatRoom(models.Model):
name = models.CharField(max_length=100, unique=True)
members = models.ManyToManyField(Member, related_name='chat_rooms')
def __str__(self):
return self.name
@python_2_unicode_compatible
class Message(models.Model):
text = models.TextField()
member = models.ForeignKey(Member, related_name='messages')
chat_room = models.ForeignKey(ChatRoom, related_name='messages')
def __str__(self):
return '{text} ({member})'.format(
text=self.text,
member=self.member
)
|
Remove the unnecessary and never-used basic auth hack. | # Universal Subtitles, universalsubtitles.org
#
# Copyright (C) 2012 Participatory Culture Foundation
#
# 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/agpl-3.0.html.
import requests
def url_exists(url):
"""Check that a url (when following redirection) exists.
This is needed because Django's validators rely on Python's urllib2 which in
verions < 2.6 won't follow redirects.
"""
try:
return 200 <= requests.head(url).status_code < 400
except requests.ConnectionError:
return False
| # Universal Subtitles, universalsubtitles.org
#
# Copyright (C) 2012 Participatory Culture Foundation
#
# 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/agpl-3.0.html.
import requests
from django.conf import settings
AUTH = getattr(settings, 'BASIC_AUTH_DOMAINS', None)
def url_exists(url):
"""Check that a url (when following redirection) exists.
This is needed because Django's validators rely on Python's urllib2
which in verions < 2.6 won't follow redirects.
"""
try:
# This AUTH stuff is a hack to get around the HTTP Basic Auth on dev
# and staging to prevent partner stuff from going public.
if AUTH:
for domain, auth in AUTH.items():
if domain in url:
return 200 <= requests.head(url, auth=auth).status_code < 400
return 200 <= requests.head(url).status_code < 400
except requests.ConnectionError:
return False
|
Test that ads appear in date order latest first | /* global describe, beforeEach, afterEach, it */
const chai = require('chai');
const should = chai.should();
const knex_config = require('../../knexfile');
const knex = require('knex')(knex_config['test']);
const util = require('../util')({ knex });
const service = require('./ads')({ knex, util });
describe('Handle ads', function() {
beforeEach(function(done) {
knex.migrate.rollback()
.then(function() {
knex.migrate.latest()
.then(function() {
return knex.seed.run()
.then(function() {
done();
});
});
});
});
afterEach(function(done) {
knex.migrate.rollback()
.then(function() {
done();
});
});
it('should list ads in order', (done) => {
service.listAds(false).then((ads) => {
ads.map(ad => ad.id).should.eql([2, 3, 1]);
done();
})
})
});
| /* global describe, beforeEach, afterEach, it */
const knex_config = require('../../knexfile');
const knex = require('knex')(knex_config['test']);
const chai = require('chai');
const should = chai.should();
describe('Handle ads', function() {
beforeEach(function(done) {
knex.migrate.rollback()
.then(function() {
knex.migrate.latest()
.then(function() {
return knex.seed.run()
.then(function() {
done();
});
});
});
});
afterEach(function(done) {
knex.migrate.rollback()
.then(function() {
done();
});
});
it('should list ads in order', (done) => {
done();
})
});
|
feat(webpack): Add heading links to documentation | const webpack = require('webpack')
const marked = require('marked')
const renderer = new marked.Renderer()
const USE_PREFETCH = process.env.NODE_ENV !== 'test'
renderer.heading = (text, level) => {
const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-')
return `<h${level}><a name="${escapedText}" href="#${escapedText}">${text}</a></h${level}>`
}
module.exports = {
webpack: config => {
// Add in prefetch conditionally so we don't break jest snapshot testing
config.plugins.push(
new webpack.DefinePlugin({
'process.env.USE_PREFETCH': JSON.stringify(USE_PREFETCH),
})
)
// Markdown loader so we can use docs as .md files
config.module.rules.push({
test: /\.md$/,
use: [
{loader: 'html-loader'},
{loader: 'markdown-loader', options: {pedantic: true, renderer}},
],
})
return config
},
}
// This is not transpiled
/*
eslint
comma-dangle: [
2,
{
arrays: 'always-multiline',
objects: 'always-multiline',
functions: 'never'
}
]
*/
| const webpack = require('webpack')
const marked = require('marked')
const renderer = new marked.Renderer()
const USE_PREFETCH = process.env.NODE_ENV !== 'test'
module.exports = {
webpack: config => {
// Add in prefetch conditionally so we don't break jest snapshot testing
config.plugins.push(
new webpack.DefinePlugin({
'process.env.USE_PREFETCH': JSON.stringify(USE_PREFETCH),
})
)
// Markdown loader so we can use docs as .md files
config.module.rules.push({
test: /\.md$/,
use: [
{loader: 'html-loader'},
{loader: 'markdown-loader', options: {pedantic: true, renderer}},
],
})
return config
},
}
// This is not transpiled
/*
eslint
comma-dangle: [
2,
{
arrays: 'always-multiline',
objects: 'always-multiline',
functions: 'never'
}
]
*/
|
Remove dryrun option from ghPages | const gulp = require('gulp');
const ghPages = require('gulp-gh-pages');
const rename = require('gulp-rename');
gulp.task('deploy', () =>
gulp.src([
'./dist/**/*',
'./docs/**/*',
], { base: '.' })
.pipe(rename(filepath => {
if (filepath.dirname.startsWith('docs')) {
// Collapses `docs` parent directory
// so index.html ends up at the root.
// `dist` remains in the dist folder.
const withoutDocs = filepath.dirname.substring('docs'.length);
const withoutLeadingSlash = withoutDocs.startsWith('/')
? withoutDocs.substring(1)
: withoutDocs;
filepath.dirname = withoutLeadingSlash;
}
}))
.pipe(ghPages())
);
| const gulp = require('gulp');
const ghPages = require('gulp-gh-pages');
const rename = require('gulp-rename');
gulp.task('deploy', () =>
gulp.src([
'./dist/**/*',
'./docs/**/*',
], { base: '.' })
.pipe(rename(filepath => {
if (filepath.dirname.startsWith('docs')) {
// Collapses `docs` parent directory
// so index.html ends up at the root.
// `dist` remains in the dist folder.
const withoutDocs = filepath.dirname.substring('docs'.length);
const withoutLeadingSlash = withoutDocs.startsWith('/')
? withoutDocs.substring(1)
: withoutDocs;
filepath.dirname = withoutLeadingSlash;
}
}))
.pipe(ghPages({ push: false }))
);
|
Add an emitter to AbstractComponent | /** @babel */
import etch from 'etch'
import {Emitter, CompositeDisposable} from 'atom'
export default class AbstractComponent {
constructor(properties, children, callback) {
if (properties) this.properties = properties
else this.properties = {}
if (children) this.children = children
else this.children = []
this.disposables = new CompositeDisposable()
this.emitter = new Emitter()
if (callback) callback(this.properties, this.children)
etch.initialize(this)
}
update(properties, children, callback) {
if (properties && this.properties !== properties) this.properties = properties
if (children && this.children !== children) this.children = children
if (callback) callback(this.properties, this.children)
return etch.update(this)
}
destroy(callback) {
this.disposables.dispose()
this.emitter.dispose()
if (callback) callback()
return etch.destroy(this)
}
}
| /** @babel */
import etch from 'etch'
import {CompositeDisposable} from 'atom'
export default class AbstractComponent {
constructor(properties, children, callback) {
if (properties) this.properties = properties
else this.properties = {}
if (children) this.children = children
else this.children = []
this.disposables = new CompositeDisposable()
if (callback) callback(this.properties, this.children)
etch.initialize(this)
}
update(properties, children, callback) {
if (properties && this.properties !== properties) this.properties = properties
if (children && this.children !== children) this.children = children
if (callback) callback(this.properties, this.children)
return etch.update(this)
}
destroy(callback) {
this.disposables.dispose()
if (callback) callback()
return etch.destroy(this)
}
}
|
Fix introduced error in test | <?php
/**
* ZnZend
*
* @author Zion Ng <zion@intzone.com>
* @link [Source] http://github.com/zionsg/ZnZend
* @since 2012-11-23T23:00+08:00
*/
namespace ZnZendTest\View\Helper;
use PHPUnit_Framework_TestCase as TestCase;
use ZnZend\View\Helper\ZnZendFormatBytes;
/**
* Tests ZnZend\View\Helper\ZnZendFormatBytes
*/
class ZnZendFormatBytesTest extends TestCase
{
/**
* Helper instance
*
* @var ZnZendFormatBytes
*/
protected $helper;
/**
* Prepares the environment before running a test.
*/
public function setUp()
{
// Constructor has no arguments
$this->helper = new ZnZendFormatBytes();
}
/**
* Cleans up the environment after running a test.
*/
protected function tearDown()
{
unset($this->helper);
}
public function testInvokeWithOneKilobyte()
{
$helper = $this->helper;
$value = 1024;
$expected = '1.00 KiB';
$actual = $helper($value);
$this->assertEquals($expected, $actual);
}
}
| <?php
/**
* ZnZend
*
* @author Zion Ng <zion@intzone.com>
* @link [Source] http://github.com/zionsg/ZnZend
* @since 2012-11-23T23:00+08:00
*/
namespace ZnZendTest\View\Helper;
use PHPUnit_Framework_TestCase as TestCase;
use ZnZend\View\Helper\ZnZendFormatBytes;
/**
* Tests ZnZend\View\Helper\ZnZendFormatBytes
*/
class ZnZendFormatBytesTest extends TestCase
{
/**
* Helper instance
*
* @var ZnZendFormatBytes
*/
protected $helper;
/**
* Prepares the environment before running a test.
*/
public function setUp()
{
// Constructor has no arguments
$this->helper = new ZnZendFormatBytes();
}
/**
* Cleans up the environment after running a test.
*/
protected function tearDown()
{
unset($this->helper);
}
public function testInvokeWithOneKilobyte()
{
$helper = $this->helper;
$value = 1024;
$expected = '1.02 KiB';
$actual = $helper($value);
$this->assertEquals($expected, $actual);
}
}
|
Complete naive solution by nested for loops | """560. Subarray Sum Equals K
Medium
Given an array of integers and an integer k, you need to find the total
number of continuous subarrays whose sum equals to k.
Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the
integer k is [-1e7, 1e7].
"""
class SolutionNaive(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
Time complexity: O(n^3).
Space complexity: O(n).
"""
count = 0
for i in range(len(nums)):
for j in range(i, len(nums)):
if sum(nums[i:(j + 1)]) == k:
count += 1
return count
def main():
import time
nums = [1, 1, 1]
k = 2
print SolutionNaive().subarraySum(nums, k)
nums = [10, 2, -2, -20, 10]
k = -10
print SolutionNaive().subarraySum(nums, k)
if __name__ == '__main__':
main()
| """560. Subarray Sum Equals K
Medium
Given an array of integers and an integer k, you need to find the total
number of continuous subarrays whose sum equals to k.
Example 1:
Input: nums = [1,1,1], k = 2
Output: 2
Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the
integer k is [-1e7, 1e7].
"""
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
pass
def main():
import time
nums = [1,1,1]
k = 2
if __name__ == '__main__':
main()
|
Fix to avoid NoneType bugs | #!/usr/bin/env python
NAME = 'Expression Engine (EllisLab)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, page = r
# There are traces found where cookie is returning values like:
# Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3
# Set-Cookie: exp_last_id=b342b432b1a876r8
if response.getheader('Set-Cookie'):
if 'exp_last_' in response.getheader('Set-Cookie'):
return True
# In-page fingerprints vary a lot in different sites. Hence these are not quite reliable.
if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')):
return True
return False | #!/usr/bin/env python
NAME = 'Expression Engine (EllisLab)'
def is_waf(self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
response, page = r
# There are traces found where cookie is returning values like:
# Set-Cookie: exp_last_query=834y8d73y94d8g983u4shn8u4shr3uh3
# Set-Cookie: exp_last_id=b342b432b1a876r8
if 'exp_last_' in response.getheader('Set-Cookie'):
return True
# In-page fingerprints vary a lot in different sites. Hence these are not quite reliable.
if any(i in page for i in (b'Invalid GET Data', b'Invalid URI')):
return True
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.