text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Revert "Changing our ``coverage`` test dependency to ``django-coverage``."
This reverts commit 68e8555cd2e07c4352ea06121ab262b19b3c2413.
Conflicts:
setup.py | from os.path import abspath, dirname, join, normpath
from setuptools import find_packages, setup
setup(
# Basic package information:
name = 'django-twilio',
version = '0.1',
packages = find_packages(),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package dependencies:
install_requires = ['twilio==3.2.3', 'Django>=1.1'],
tests_require = ['django-nose>=0.1.3', 'coverage>=3.5'],
# Metadata for PyPI:
author = 'Randall Degges',
author_email = 'rdegges@gmail.com',
license = 'UNLICENSE',
url = 'http://twilio.com/',
keywords = 'twilio telephony call phone voip sms',
description = 'A simple library for building twilio-powered Django webapps.',
long_description = open(normpath(join(dirname(abspath(__file__)), 'README'))).read()
)
| from os.path import abspath, dirname, join, normpath
from setuptools import find_packages, setup
setup(
# Basic package information:
name = 'django-twilio',
version = '0.1',
packages = find_packages(),
# Packaging options:
zip_safe = False,
include_package_data = True,
# Package dependencies:
install_requires = ['twilio==3.2.3', 'Django>=1.1'],
tests_require = ['django-nose==0.1.3', 'django-coverage==1.2.1'],
# Metadata for PyPI:
author = 'Randall Degges',
author_email = 'rdegges@gmail.com',
license = 'UNLICENSE',
url = 'http://twilio.com/',
keywords = 'twilio telephony call phone voip sms',
description = 'A simple library for building twilio-powered Django webapps.',
long_description = open(normpath(join(dirname(abspath(__file__)), 'README'))).read()
)
|
Support for any type of geometry in fit_source. | requirejs(["mapboxgl"], function(mapboxgl) {
var map = window.__jm_maps["{{uuid}}"];
var findBounds = function(bounds, coordinates) {
if (coordinates[0] instanceof Array) {
coordinates.forEach(function(c) {
bounds = findBounds(bounds, c);
});
} else {
if (bounds === undefined) {
bounds = new mapboxgl.LngLatBounds(coordinates, coordinates);
} else {
bounds = bounds.extend(coordinates);
}
}
return bounds;
}
var run = function() {
var source = map.getSource("{{source_uuid}}");
var geojson = source._data;
var bounds = undefined;
geojson.features.forEach(function(feature) {
bounds = findBounds(bounds, feature.geometry.coordinates);
});
map.fitBounds(bounds, {
padding: {{padding}}
});
}
if (map._loaded) {
run();
} else {
map.on("load", run);
}
});
| requirejs(["mapboxgl"], function(mapboxgl) {
var map = window.__jm_maps["{{uuid}}"];
var run = function() {
var source = map.getSource("{{source_uuid}}");
var geojson = source._data;
var coordinates = geojson.features[0].geometry.coordinates[0];
if (coordinates[0] instanceof Array) {
coordinates = coordinates[0];
}
var bounds = new mapboxgl.LngLatBounds(coordinates, coordinates);
geojson.features.forEach(function(feature) {
coordinates = feature.geometry.coordinates;
if (coordinates[0] instanceof Array) {
coordinates = coordinates[0];
}
bounds = coordinates.reduce(function(bounds, coord) {
return bounds.extend(coord);
}, bounds);
});
map.fitBounds(bounds, {
padding: {{padding}}
});
}
if (map._loaded) {
run();
} else {
map.on("load", run);
}
});
|
Change add to return the vector itself, for method chaining | /**
* Creates a new 2 dimensional Vector.
*
* @constructor
* @this {Circle}
* @param {number} x The x value of the new vector.
* @param {number} y The y value of the new vector.
*/
function Vector2(x, y) {
if (typeof x === 'undefined') {
x = 0;
}
if (typeof y === 'undefined') {
y = 0;
}
this.x = x;
this.y = y;
}
Vector2.prototype.add = function(v) {
if ( !(v instanceof Vector2) ) {
throw new InvalidArgumentError("v", "You can only add a vector to another vector! The object passed was: " + v);
}
this.x += v.x;
this.y += v.y;
return this;
}
Vector2.prototype.toString = function() {
return "[" + this.x + ", " + this.y + "]";
} | /**
* Creates a new 2 dimensional Vector.
*
* @constructor
* @this {Circle}
* @param {number} x The x value of the new vector.
* @param {number} y The y value of the new vector.
*/
function Vector2(x, y) {
if (typeof x === 'undefined') {
x = 0;
}
if (typeof y === 'undefined') {
y = 0;
}
this.x = x;
this.y = y;
}
Vector2.prototype.add = function(v) {
if ( !(v instanceof Vector2) ) {
throw new InvalidArgumentError("v", "You can only add a vector to another vector! The object passed was: " + v);
}
this.x += v.x;
this.y += v.y;
}
Vector2.prototype.toString = function() {
return "[" + this.x + ", " + this.y + "]";
} |
Fix CSP error caused by nyc instrumentation
This had been fixed earlier, however the regular expression no longer matched | 'use strict';
const {Transform} = require('stream');
const {createInstrumenter} = require('istanbul-lib-instrument');
const instrumenter = createInstrumenter({
coverageVariable: '__runner_coverage__',
preserveComments: true,
compact: false,
esModules: false,
autoWrap: false,
produceSourceMap: false,
sourceMapUrlCallback: null,
debug: false,
});
const scriptContent = Symbol('scriptContent');
const scriptFileName = Symbol('scriptFileName');
class CoverageInstrumentationStream extends Transform {
constructor(options, fileName) {
super(options);
this[scriptContent] = '';
this[scriptFileName] = fileName;
}
_transform(data, encoding, callback) {
this[scriptContent] += data;
callback(null);
}
_flush(callback) {
let instrumented = instrumenter.instrumentSync(this[scriptContent], this[scriptFileName]);
// Hack for CSP Compatibility
instrumented = instrumented.replace(/global\s*=\s*new\s+Function\(['"]return this['"]\)\(\)/g, 'global = self');
callback(null, instrumented);
}
}
module.exports = CoverageInstrumentationStream;
| 'use strict';
const {Transform} = require('stream');
const {createInstrumenter} = require('istanbul-lib-instrument');
const instrumenter = createInstrumenter({
coverageVariable: '__runner_coverage__',
preserveComments: true,
compact: false,
esModules: false,
autoWrap: false,
produceSourceMap: false,
sourceMapUrlCallback: null,
debug: false,
});
const scriptContent = Symbol('scriptContent');
const scriptFileName = Symbol('scriptFileName');
class CoverageInstrumentationStream extends Transform {
constructor(options, fileName) {
super(options);
this[scriptContent] = '';
this[scriptFileName] = fileName;
}
_transform(data, encoding, callback) {
this[scriptContent] += data;
callback(null);
}
_flush(callback) {
let instrumented = instrumenter.instrumentSync(this[scriptContent], this[scriptFileName]);
// Hack for CSP Compatibility
instrumented = instrumented.replace(/global\s*=\s*new\s+Function\('return this'\)\(\),/g, 'global = self,');
callback(null, instrumented);
}
}
module.exports = CoverageInstrumentationStream;
|
Change the Export label to match style directives | package com.codenvy.ide.ext.datasource.client.sqllauncher;
import com.google.gwt.i18n.client.LocalizableResource.DefaultLocale;
import com.google.gwt.i18n.client.Messages;
@DefaultLocale("en")
public interface SqlRequestLauncherConstants extends Messages {
@DefaultMessage("Open SQL editor")
String menuEntryOpenSqlEditor();
@DefaultMessage("SQL editor")
String sqlEditorWindowTitle();
@DefaultMessage("Select datasource")
String selectDatasourceLabel();
@DefaultMessage("Result limit")
String resultLimitLabel();
@DefaultMessage("Execute")
String executeButtonLabel();
@DefaultMessage("{0} rows.")
@AlternateMessage({"one", "{0} row."})
String updateCountMessage(@PluralCount int count);
@DefaultMessage("Export")
String exportCsvLabel();
@DefaultMessage("Execution mode")
String executionModeLabel();
@DefaultMessage("Execute all - ignore and report errors")
String executeAllModeItem();
@DefaultMessage("First error - stop on first error")
String stopOnErrorModeitem();
@DefaultMessage("Transaction - rollback on first error")
String transactionModeItem();
}
| package com.codenvy.ide.ext.datasource.client.sqllauncher;
import com.google.gwt.i18n.client.LocalizableResource.DefaultLocale;
import com.google.gwt.i18n.client.Messages;
@DefaultLocale("en")
public interface SqlRequestLauncherConstants extends Messages {
@DefaultMessage("Open SQL editor")
String menuEntryOpenSqlEditor();
@DefaultMessage("SQL editor")
String sqlEditorWindowTitle();
@DefaultMessage("Select datasource")
String selectDatasourceLabel();
@DefaultMessage("Result limit")
String resultLimitLabel();
@DefaultMessage("Execute")
String executeButtonLabel();
@DefaultMessage("{0} rows.")
@AlternateMessage({"one", "{0} row."})
String updateCountMessage(@PluralCount int count);
@DefaultMessage("Export as CSV file")
String exportCsvLabel();
@DefaultMessage("Execution mode")
String executionModeLabel();
@DefaultMessage("Execute all - ignore and report errors")
String executeAllModeItem();
@DefaultMessage("First error - stop on first error")
String stopOnErrorModeitem();
@DefaultMessage("Transaction - rollback on first error")
String transactionModeItem();
}
|
Fix failing test and make lint | import flask
from donut.modules.groups import helpers as groups
def has_permission(user_id, permission_id):
'''
Returns True if [user_id] holds a position that directly
or indirectly (through a position relation) grants
them [permission_id]. Otherwise returns False.
'''
if not (isinstance(user_id, int) and isinstance(permission_id, int)):
return False
# get all position id's with this permission
query = '''SELECT pos_id FROM position_permissions WHERE permission_id = %s'''
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, permission_id)
result = cursor.fetchall()
pos_ids = [row['pos_id'] for row in result]
for pos_id in pos_ids:
holders = groups.get_position_holders(pos_id)
holders = [row['user_id'] for row in holders]
if user_id in holders:
return True
return False
| import flask
from donut.modules.groups import helpers as groups
def has_permission(user_id, permission_id):
'''
Returns True if [user_id] holds a position that directly
or indirectly (through a position relation) grants
them [permission_id]. Otherwise returns False.
'''
if not (isinstance(user_id, int) and isinstance(permission_id, int)):
return False
# get all position id's with this permission
query = '''SELECT pos_id FROM position_permissions WHERE permission_id = %s'''
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, permission_id)
result = cursor.fetchall()
pos_ids = [row['pos_id'] for row in result]
for pos_id in pos_ids:
holders = groups.get_position_holders(pos_id)
if {'user_id': user_id} in holders:
return True
return False
|
Allow max 20MB file chunks | # Goal: Store settings which can be over-ruled
# using environment variables.
#
# @authors:
# Andrei Sura <sura.andrei@gmail.com>
# Ruchi Vivek Desai <ruchivdesai@gmail.com>
# Sanath Pasumarthy <sanath@ufl.edu>
#
# @TODO: add code to check for valid paths
import os
# Limit the max upload size for the app to 20 MB
# @see https://pythonhosted.org/Flask-Uploads/
DEFAULT_MAX_CONTENT_LENGTH = 20 * 1024 * 1024
MAX_CONTENT_LENGTH = os.getenv('REDI_DROPPER_MAX_CONTENT_LENGTH', DEFAULT_MAX_CONTENT_LENGTH)
DB_USER = os.getenv('REDI_DROPPER_DB_USER', 'redidropper')
DB_PASS = os.getenv('REDI_DROPPER_DB_PASS', 'securepass')
# http://effbot.org/librarybook/os-path.htm
INCOMING_TEMP_DIR = os.getenv('REDI_DROPPER_INCOMING_TEMP_DIR', \
os.path.expanduser('~/.redidropper/incoming/temp'))
INCOMING_SAVED_DIR = os.getenv('REDI_DROPPER_NCOMING_SAVED_DIR',\
os.path.expanduser('~/.redidropper/incoming/saved'))
| # Goal: Store settings which can be over-ruled
# using environment variables.
#
# @authors:
# Andrei Sura <sura.andrei@gmail.com>
# Ruchi Vivek Desai <ruchivdesai@gmail.com>
# Sanath Pasumarthy <sanath@ufl.edu>
#
# @TODO: add code to check for valid paths
import os
DB_USER = os.getenv('REDI_DROPPER_DB_USER', 'redidropper')
DB_PASS = os.getenv('REDI_DROPPER_DB_PASS', 'securepass')
# http://effbot.org/librarybook/os-path.htm
INCOMING_TEMP_DIR = os.getenv('REDI_DROPPER_INCOMING_TEMP_DIR', \
os.path.expanduser('~/.redidropper/incoming/temp'))
INCOMING_SAVED_DIR = os.getenv('REDI_DROPPER_NCOMING_SAVED_DIR',\
os.path.expanduser('~/.redidropper/incoming/saved'))
|
Improve the GAPI mocks for local development. | // GAPI Hangouts Mocks
var gapi = function(gapi){
// Create the Hangout API
gapi.hangout = function(hangout){
hangout.localParticipant = {
id: '123456',
displayIndex: 0,
person: {
id: '123456',
displayName: 'Test'
}
};
// OnApiReady Mocks
hangout.onApiReady = {
add: function(callback){
// Let's just go ahead and call it.
// No sense wasting time.
callback({ isApiReady: true });
}
};
// Data Mocks
var _dataChangedCallbacks = [];
hangout.data = {
currentState: {},
getState: function(){ return hangout.data.currentState; },
setValue: function(key, value){ hangout.data.currentState[key] = value; },
submitDelta: function(delta){ console.log(delta); },
onStateChanged: {
add: function(callback){ _dataChangedCallbacks.push(callback); }
}
};
hangout.getLocalParticipant = function(){ return hangout.localParticipant; };
return hangout;
}(gapi.hangout || {});
return gapi;
}(gapi || {});
| // GAPI Hangouts Mocks
var gapi = function(gapi){
// Create the Hangout API
gapi.hangout = function(hangout){
hangout.localParticipant = {
id: '123456',
displayIndex: 0,
person: {
id: '123456',
displayName: 'Test'
}
};
// OnApiReady Mocks
hangout.onApiReady = {
add: function(callback){
// Let's just go ahead and call it.
// No sense wasting time.
callback({ isApiReady: true });
}
};
// Data Mocks
var _dataChangedCallbacks = [];
hangout.data = {
currentState: {},
getState: function(){ return hangout.data.currentState; },
setValue: function(key, value){ hangout.data.currentState[key] = value; },
onStateChanged: {
add: function(callback){ _dataChangedCallbacks.push(callback); }
}
};
hangout.getLocalParticipant = function(){ return hangout.localParticipant; };
return hangout;
}(gapi.hangout || {});
return gapi;
}(gapi || {});
|
Add forgotten prop check on test | /* global request, describe, it, before */
import '../../setup'
import { app } from '../../../src/lib/app'
const url = 'http://localhost:8181/api/'
describe('app', () => {
before(() => {
// Start app
app({
port: 8181,
lambdas: './test/lambdas'
})
})
it('responds with the correct operation', (done) => {
request(url)
.get('test')
.expect(200)
.end((err, res) => {
if (err) throw err
res.body.should.have.property('operation')
res.body.operation.should.equal('GET')
done()
})
})
it('responds with correct property value', (done) => {
request(url)
.post('test')
.send({ foo: 'bar' })
.end((err, res) => {
if (err) throw err
res.body.should.have.property('foo')
res.body.foo.should.equal('bar')
done()
})
})
}) | /* global request, describe, it, before */
import '../../setup'
import { app } from '../../../src/lib/app'
const url = 'http://localhost:8181/api/'
describe('app', () => {
before(() => {
// Start app
app({
port: 8181,
lambdas: './test/lambdas'
})
})
it('responds with the correct operation', (done) => {
request(url)
.get('test')
.expect(200, done)
})
it('responds with correct property value', (done) => {
request(url)
.post('test')
.send({ foo: 'bar' })
.end((err, res) => {
if (err) {
throw err
}
res.body.should.have.property('foo')
res.body.foo.should.equal('bar')
done()
})
})
}) |
Add test for alternate version of cast credit | import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8)
def test_is_cast_credit(self):
cast1 = 'Bryan Cranston - Walter White'.split()
cast2 = 'Giancarlo Esposito - Gustavo "Gus" Fring'.split()
self.assertTrue(wikiquote.is_cast_credit(cast1))
self.assertTrue(wikiquote.is_cast_credit(cast2))
| import wikiquote
import unittest
class QuotesTest(unittest.TestCase):
"""
Test wikiquote.quotes()
"""
def test_disambiguation(self):
self.assertRaises(wikiquote.DisambiguationPageException,
wikiquote.quotes,
'Matrix')
def test_no_such_page(self):
self.assertRaises(wikiquote.NoSuchPageException,
wikiquote.quotes,
'aaksejhfkasehfksdfsa')
def test_normal_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)')
self.assertTrue(len(quotes) > 0)
def test_max_quotes(self):
quotes = wikiquote.quotes('The Matrix (film)', max_quotes = 8)
self.assertEqual(len(quotes), 8) |
Allow 'scenario-name' to be null if it does not exist | from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c in cea.plots.categories.list_categories()}
@api.route('/')
class Dashboard(Resource):
def get(self):
"""
Get Dashboards from yaml file
"""
config = cea.config.Configuration()
plot_cache = cea.plots.cache.PlotCache(config)
dashboards = cea.plots.read_dashboards(config, plot_cache)
return [{'name': d.name, 'description': d.description, 'layout': d.layout if d.layout in LAYOUTS else 'row',
'plots': [{'title': plot.title, 'scenario':
plot.parameters['scenario-name'] if 'scenario-name' in plot.parameters.keys() else None}
for plot in d.plots]} for d in dashboards]
| from flask_restplus import Namespace, Resource, fields, abort
import cea.config
import cea.plots.cache
api = Namespace('Dashboard', description='Dashboard plots')
LAYOUTS = ['row', 'grid', 'map']
CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]}
for c in cea.plots.categories.list_categories()}
@api.route('/')
class Dashboard(Resource):
def get(self):
"""
Get Dashboards from yaml file
"""
config = cea.config.Configuration()
plot_cache = cea.plots.cache.PlotCache(config)
dashboards = cea.plots.read_dashboards(config, plot_cache)
return [{'name': d.name, 'description': d.description, 'layout': d.layout if d.layout in LAYOUTS else 'row',
'plots': [{'title': plot.title, 'scenario': plot.parameters['scenario-name']} for plot in d.plots]} for d in dashboards]
|
Remove typescript, as it is not compiled by rnpm | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
const path = require('path');
function findXcodeProject(files) {
const sortedFiles = files.sort();
for (let i = sortedFiles.length - 1; i >= 0; i--) {
const fileName = files[i];
const ext = path.extname(fileName);
if (ext === '.xcworkspace') {
return {
name: fileName,
isWorkspace: true,
};
}
if (ext === '.xcodeproj') {
return {
name: fileName,
isWorkspace: false,
};
}
}
return null;
}
module.exports = findXcodeProject;
| /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
const path = require('path');
type ProjectInfo = {
name: string;
isWorkspace: boolean;
}
function findXcodeProject(files: Array<string>): ?ProjectInfo {
const sortedFiles = files.sort();
for (let i = sortedFiles.length - 1; i >= 0; i--) {
const fileName = files[i];
const ext = path.extname(fileName);
if (ext === '.xcworkspace') {
return {
name: fileName,
isWorkspace: true,
};
}
if (ext === '.xcodeproj') {
return {
name: fileName,
isWorkspace: false,
};
}
}
return null;
}
module.exports = findXcodeProject;
|
Check that engine fight files are deleted before test | #!/usr/bin/python
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
if os.path.isfile(game_file):
print('Could not delete output file:', game_file)
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
| #!/usr/bin/python
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
|
Fix detecting css output folder in different jasy versions | # Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profile, regenerate = False):
""" Build static website """
def getPartUrl(part, type):
folder = ""
if type == "css":
if hasattr(profile, "getCssFolder"):
# Old jasy < 1.5-beta4
folder = profile.getCssFolder()
else:
# New jasy >= 1.5-beta4
folder = profile.getCssOutputFolder()
outputPath = os.path.relpath(os.path.join(profile.getDestinationPath(), folder), profile.getWorkingPath())
filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type))
return filename
profile.addCommand("part.url", getPartUrl, "url")
for permutation in profile.permutate():
konstrukteur.Konstrukteur.build(regenerate, profile)
| # Little helper to allow python modules in current jasylibrarys path
import sys, os.path, inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
sys.path.append(path)
import konstrukteur.Konstrukteur
import jasy.asset.Manager
@share
def build(profile, regenerate = False):
""" Build static website """
def getPartUrl(part, type):
folder = ""
if type == "css":
folder = profile.getCssFolder()
outputPath = os.path.relpath(os.path.join(profile.getDestinationPath(), folder), profile.getWorkingPath())
filename = profile.expandFileName("%s/%s-{{id}}.%s" % (outputPath, part, type))
return filename
profile.addCommand("part.url", getPartUrl, "url")
for permutation in profile.permutate():
konstrukteur.Konstrukteur.build(regenerate, profile)
|
Update to support new module API
https://github.com/facebook/react-native/commit/bc28a35bda0e358a8296a7b53eb7315b736c6e4b
- modules are no longer plain objects
- `isPolyfill` is now a function
- `id` is now retrieved asynchronously with `getName` | 'use strict';
var path = require('path');
/**
* Extract the React Native module paths
*
* @return {Promise<Object>} A promise which resolves with
* a webpack 'externals' configuration object
*/
function getReactNativeExternals() {
var reactNativeRoot = path.dirname(require.resolve('react-native/package'));
var blacklist = require('react-native/packager/blacklist');
var ReactPackager = require('react-native/packager/react-packager');
var reactNativePackage = require('react-native/package');
return ReactPackager.getDependencies({
assetRoots: [reactNativeRoot],
blacklistRE: blacklist(false /* don't blacklist any platform */),
projectRoots: [reactNativeRoot],
transformModulePath: require.resolve('react-native/packager/transformer')
}, reactNativePackage.main).then(function(dependencies) {
return dependencies.filter(function(dependency) {
return !dependency.isPolyfill();
});
}).then(function(dependencies) {
return Promise.all(dependencies.map(function(dependency) {
return dependency.getName();
}));
}).then(function(moduleIds) {
return moduleIds.reduce(function(externals, moduleId) {
externals[moduleId] = 'commonjs ' + moduleId
return externals;
}, {});
});
}
module.exports = getReactNativeExternals;
| 'use strict';
var path = require('path');
/**
* Extract the React Native module paths
*
* @return {Promise<Object>} A promise which resolves with
* a webpack 'externals' configuration object
*/
function getReactNativeExternals() {
var reactNativeRoot = path.dirname(require.resolve('react-native/package'));
var blacklist = require('react-native/packager/blacklist');
var ReactPackager = require('react-native/packager/react-packager');
var reactNativePackage = require('react-native/package');
return ReactPackager.getDependencies({
assetRoots: [reactNativeRoot],
blacklistRE: blacklist(false /* don't blacklist any platform */),
projectRoots: [reactNativeRoot],
transformModulePath: require.resolve('react-native/packager/transformer')
}, reactNativePackage.main).then(function(dependencies) {
return dependencies.filter(function(dependency) {
return !dependency.isPolyfill;
});
}).then(function(dependencies) {
return dependencies.reduce(function(externals, dependency) {
externals[dependency.id] = 'commonjs ' + dependency.id;
return externals;
}, {});
});
}
module.exports = getReactNativeExternals;
|
Clear localStorage order variables when order is complete | SpreeStore.module('Checkout',function(Checkout, SpreeStore, Backbone,Marionette,$,_){
Checkout.Controller = {
show: function(state) {
SpreeStore.noSidebar()
order = new SpreeStore.Models.Order({ number: SpreeStore.current_order_id })
order.fetch({
data: $.param({ order_token: SpreeStore.current_order_token}),
success: function(order) {
if (order.attributes.state == "complete") {
window.localStorage.removeItem('current_order_id');
window.localStorage.removeItem('current_order_token');
SpreeStore.navigate("/orders/" + order.attributes.number, true)
} else {
Checkout.Controller.renderFor(order, state)
}
}
})
},
renderFor: function(order, state) {
state = state || order.attributes.state
SpreeStore.navigate("/checkout/" + state)
orderView = Checkout[state + 'View']
if (orderView != undefined) {
SpreeStore.mainRegion.show(new orderView({model: order}))
} else {
SpreeStore.navigate("/checkout/" + order.attributes.state)
this.renderFor(order, order.attributes.state)
}
}
}
}) | SpreeStore.module('Checkout',function(Checkout, SpreeStore, Backbone,Marionette,$,_){
Checkout.Controller = {
show: function(state) {
SpreeStore.noSidebar()
order = new SpreeStore.Models.Order({ number: SpreeStore.current_order_id })
order.fetch({
data: $.param({ order_token: SpreeStore.current_order_token}),
success: function(order) {
if (order.attributes.state == "complete") {
SpreeStore.navigate("/orders/" + order.attributes.number, true)
} else {
Checkout.Controller.renderFor(order, state)
}
}
})
},
renderFor: function(order, state) {
state = state || order.attributes.state
SpreeStore.navigate("/checkout/" + state)
orderView = Checkout[state + 'View']
if (orderView != undefined) {
SpreeStore.mainRegion.show(new orderView({model: order}))
} else {
SpreeStore.navigate("/checkout/" + order.attributes.state)
this.renderFor(order, order.attributes.state)
}
}
}
}) |
[PLAT-3891] Exit with -1 status if server failed to start up | /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.integration.timeseries.snapshot;
import com.opengamma.component.OpenGammaComponentServer;
/**
* Historical timeseries snapshotter.
*/
public class HistoricalTimeSeriesSnapshotter extends OpenGammaComponentServer {
/**
* Main method to start an OpenGamma JVM process for development.
*
* @param args the arguments
*/
public static void main(String[] args) { // CSIGNORE
if (args.length == 0) {
// if no command line arguments, then use default arguments suitable for development in an IDE
// the first argument is for verbose startup, to aid understanding
// the second argument defines the start of a chain of properties files providing the configuration
args = new String[] {"-v", "classpath:/htssnapshot/hts-snapshot.properties"};
}
if (!new HistoricalTimeSeriesSnapshotter().run(args)) {
System.exit(-1);
}
}
}
| /**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.integration.timeseries.snapshot;
import com.opengamma.component.OpenGammaComponentServer;
/**
* Historical timeseries snapshotter.
*/
public class HistoricalTimeSeriesSnapshotter extends OpenGammaComponentServer {
/**
* Main method to start an OpenGamma JVM process for development.
*
* @param args the arguments
*/
public static void main(String[] args) { // CSIGNORE
if (args.length == 0) {
// if no command line arguments, then use default arguments suitable for development in an IDE
// the first argument is for verbose startup, to aid understanding
// the second argument defines the start of a chain of properties files providing the configuration
args = new String[] {"-v", "classpath:/htssnapshot/hts-snapshot.properties"};
}
new HistoricalTimeSeriesSnapshotter().run(args);
}
}
|
Fix getting size into options form | editor.registerElementHandler('spacer', new function() {
Element.apply(this, arguments);
this.editor;
this.getName = function() {
return 'spacer';
};
this.getIcon = function() {
return "fa-arrows-v";
};
this.defaultOptions = { 'size': '25' };
this.getToolbarButtons = function() {
let handler = this;
return {
options: {
icon: "fa-gear",
click: function(elementDom){
handler.openOptionsForm(elementDom);
}
}
};
};
this.getOptionsFormSettings = function() {
return {
onShow: function(form, options){
if (!options || !options.size) { return; }
$('#size', form).val(options.size);
}
};
};
this.onCreateElement = function(elementDom) {
this.openOptionsForm(elementDom);
};
this.applyOptions = function(elementDom, form) {
let size = $('#size',form).val();
let elementId = elementDom.attr('id');
options = this.getOptions(elementId);
options['size'] = size;
$('div.jodelcms-content div', elementDom).css('height', Number(size)+'px');
};
}); | editor.registerElementHandler('spacer', new function() {
Element.apply(this, arguments);
this.editor;
this.getName = function() {
return 'spacer';
};
this.getIcon = function() {
return "fa-arrows-v";
};
this.defaultOptions = { 'size': '25' };
this.getToolbarButtons = function() {
let handler = this;
return {
options: {
icon: "fa-gear",
click: function(elementDom){
handler.openOptionsForm(elementDom);
}
}
};
};
this.getOptionsFormSettings = function() {
return {
onShow: function(form, options){
if (!options || !options.size) { return; }
//$('#size', form).val(options.size);
}
};
};
this.onCreateElement = function(elementDom) {
this.openOptionsForm(elementDom);
};
this.applyOptions = function(elementDom, form) {
let size = $('#size',form).val();
let elementId = elementDom.attr('id');
options = this.getOptions(elementId);
options['size'] = size;
$('div.jodelcms-content div', elementDom).css('height', Number(size)+'px');
};
}); |
Fix slugify for use without validator | import codecs
from django.core import exceptions
from django.utils import text
import translitcodec
def no_validator(arg):
pass
def slugify(model, field, value, validator=no_validator):
orig_slug = slug = text.slugify(codecs.encode(value, 'translit/long'))[:45]
i = 0
while True:
try:
try:
validator(slug)
except exceptions.ValidationError:
pass
else:
model.objects.get(**{field: slug})
i += 1
slug = orig_slug + '-' + str(i)
except model.DoesNotExist:
return slug
| import codecs
from django.core import exceptions
from django.utils import text
import translitcodec
def slugify(model, field, value, validator):
orig_slug = slug = text.slugify(codecs.encode(value, 'translit/long'))[:45]
i = 0
while True:
try:
try:
validator(slug)
except exceptions.ValidationError:
pass
else:
model.objects.get(**{field: slug})
i += 1
slug = orig_slug + '-' + str(i)
except model.DoesNotExist:
return slug
|
Use `_.extend` instead of `Object.assign` in Node code
…to support environments without ES2015 support | module.exports = function bindSassMiddleware (keystone, app) {
// the sass option can be a single path, or array of paths
// when set, we configure the node-sass middleware
var sassPaths = keystone.get('sass');
var sassOptions = keystone.get('sass options') || {};
var debug = require('debug')('keystone:core:bindSassMiddleware');
var _ = require('underscore');
if (typeof sassPaths === 'string') {
sassPaths = [sassPaths];
}
if (Array.isArray(sassPaths)) {
var sassMiddleware;
try {
debug('adding sass');
sassMiddleware = require('node-sass-middleware');
} catch(e) {
if (e.code === 'MODULE_NOT_FOUND') {
console.error(
'\nERROR: node-sass not found.\n' +
'\nPlease install the node-sass-middleware from npm to use the `sass` option.' +
'\nYou can do this by running "npm install node-sass-middleware --save".\n'
);
process.exit(1);
} else {
throw e;
}
}
sassPaths.forEach(function(path) {
app.use(sassMiddleware(_.extend({
src: keystone.expandPath(path),
dest: keystone.expandPath(path),
outputStyle: keystone.get('env') === 'production' ? 'compressed' : 'nested'
}, sassOptions)));
});
}
};
| module.exports = function bindSassMiddleware (keystone, app) {
// the sass option can be a single path, or array of paths
// when set, we configure the node-sass middleware
var sassPaths = keystone.get('sass');
var sassOptions = keystone.get('sass options') || {};
var debug = require('debug')('keystone:core:bindSassMiddleware');
if (typeof sassPaths === 'string') {
sassPaths = [sassPaths];
}
if (Array.isArray(sassPaths)) {
var sassMiddleware;
try {
debug('adding sass');
sassMiddleware = require('node-sass-middleware');
} catch(e) {
if (e.code === 'MODULE_NOT_FOUND') {
console.error(
'\nERROR: node-sass not found.\n' +
'\nPlease install the node-sass-middleware from npm to use the `sass` option.' +
'\nYou can do this by running "npm install node-sass-middleware --save".\n'
);
process.exit(1);
} else {
throw e;
}
}
sassPaths.forEach(function(path) {
app.use(sassMiddleware(Object.assign({
src: keystone.expandPath(path),
dest: keystone.expandPath(path),
outputStyle: keystone.get('env') === 'production' ? 'compressed' : 'nested'
}, sassOptions)));
});
}
};
|
Include AllValuesQuantizer in external APIs
PiperOrigin-RevId: 320104499 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Module containing Quantization abstraction and quantizers."""
# quantize with custom quantization parameterization or implementation, or
# handle custom Keras layers.
from tensorflow_model_optimization.python.core.quantization.keras.quantizers import AllValuesQuantizer
from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer
from tensorflow_model_optimization.python.core.quantization.keras.quantizers import MovingAverageQuantizer
from tensorflow_model_optimization.python.core.quantization.keras.quantizers import Quantizer
| # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Module containing Quantization abstraction and quantizers."""
# quantize with custom quantization parameterization or implementation, or
# handle custom Keras layers.
from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer
from tensorflow_model_optimization.python.core.quantization.keras.quantizers import MovingAverageQuantizer
from tensorflow_model_optimization.python.core.quantization.keras.quantizers import Quantizer
|
Fix typo in database migration script. | # Generated by Django 2.2.13 on 2020-11-23 13:44
from django.db import migrations, models
def fill_new_geo_fields(apps, schema_editor):
Offering = apps.get_model('marketplace', 'Offering')
for offering in Offering.objects.all():
if offering.geolocations:
geolocation = offering.geolocations[0]
offering.latitude = geolocation['latitude']
offering.longitude = geolocation['longitude']
offering.save()
class Migration(migrations.Migration):
dependencies = [
('marketplace', '0033_mandatory_offering_type'),
]
operations = [
migrations.AddField(
model_name='offering',
name='latitude',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='offering',
name='longitude',
field=models.FloatField(blank=True, null=True),
),
migrations.RunPython(fill_new_geo_fields),
migrations.RemoveField(model_name='offering', name='geolocations',),
]
| # Generated by Django 2.2.13 on 2020-11-23 13:44
from django.db import migrations, models
def fill_new_geo_fields(apps, schema_editor):
Offering = apps.get_model('marketplace', 'Offering')
for offering in Offering.objects.all():
if not offering.geolocations:
geolocation = offering.geolocations[0]
offering.latitude = geolocation['latitude']
offering.longitude = geolocation['longitude']
offering.save()
class Migration(migrations.Migration):
dependencies = [
('marketplace', '0033_mandatory_offering_type'),
]
operations = [
migrations.AddField(
model_name='offering',
name='latitude',
field=models.FloatField(blank=True, null=True),
),
migrations.AddField(
model_name='offering',
name='longitude',
field=models.FloatField(blank=True, null=True),
),
migrations.RunPython(fill_new_geo_fields),
migrations.RemoveField(model_name='offering', name='geolocations',),
]
|
Fix small incompatibility with Python 3.2 | from __future__ import absolute_import
import sys
from ast import *
from .version_info import PY2
if PY2 or sys.version_info[1] <= 2:
Try = TryExcept
else:
TryFinally = ()
if PY2:
def argument_names(node):
return [isinstance(arg, Name) and arg.id or None for arg in node.args.args]
def kw_only_argument_names(node):
return []
def kw_only_default_count(node):
return 0
else:
def argument_names(node):
return [arg.arg for arg in node.args.args]
def kw_only_argument_names(node):
return [arg.arg for arg in node.args.kwonlyargs]
def kw_only_default_count(node):
return sum(1 for n in node.args.kw_defaults if n is not None)
| from __future__ import absolute_import
from ast import *
from .version_info import PY2
if PY2:
Try = TryExcept
def argument_names(node):
return [isinstance(arg, Name) and arg.id or None for arg in node.args.args]
def kw_only_argument_names(node):
return []
def kw_only_default_count(node):
return 0
else:
TryFinally = ()
def argument_names(node):
return [arg.arg for arg in node.args.args]
def kw_only_argument_names(node):
return [arg.arg for arg in node.args.kwonlyargs]
def kw_only_default_count(node):
return sum(1 for n in node.args.kw_defaults if n is not None)
|
Disable csrf checks for voting | from django.conf.urls import patterns, url
from django.views.decorators.csrf import csrf_exempt
# for voting
from voting.views import vote_on_object
from bookmarks.models import Bookmark
urlpatterns = patterns('',
url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"),
url(r'^your_bookmarks/$', 'bookmarks.views.your_bookmarks', name="your_bookmarks"),
url(r'^add/$', 'bookmarks.views.add', name="add_bookmark"),
url(r'^(\d+)/delete/$', 'bookmarks.views.delete', name="delete_bookmark_instance"),
# for voting
(r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
csrf_exempt(vote_on_object), dict(
model=Bookmark,
template_object_name='bookmark',
template_name='kb/link_confirm_vote.html',
allow_xmlhttprequest=True)),
)
| from django.conf.urls import patterns, url
# for voting
from voting.views import vote_on_object
from bookmarks.models import Bookmark
urlpatterns = patterns('',
url(r'^$', 'bookmarks.views.bookmarks', name="all_bookmarks"),
url(r'^your_bookmarks/$', 'bookmarks.views.your_bookmarks', name="your_bookmarks"),
url(r'^add/$', 'bookmarks.views.add', name="add_bookmark"),
url(r'^(\d+)/delete/$', 'bookmarks.views.delete', name="delete_bookmark_instance"),
# for voting
(r'^(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
vote_on_object, dict(
model=Bookmark,
template_object_name='bookmark',
template_name='kb/link_confirm_vote.html',
allow_xmlhttprequest=True)),
)
|
Remove duplicate labels from Date fields. | package todomore.android.metawidget;
import java.util.Map;
import org.metawidget.android.widget.AndroidMetawidget;
import org.metawidget.widgetbuilder.iface.WidgetBuilder;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.darwinsys.todo.model.Date;
public class TodoMoreAndroidWidgetBuilder implements WidgetBuilder<View, AndroidMetawidget> {
private static final String TAG = "TAWB";
public TodoMoreAndroidWidgetBuilder() {
Log.d(TAG, "TodoAndroidWidgetBuilder()");
// empty
}
@Override
public View buildWidget(String elementName,
Map<String, String> attributes,
AndroidMetawidget metaWidget) {
// Log.d(TAG, String.format("buildWidget(%s, %s, %s)", elementName, attributes, metaWidget));
Context context = metaWidget.getContext();
String type = attributes.get("type");
String readOnlyStr = attributes.get("read-only");
boolean readOnly = Boolean.parseBoolean(readOnlyStr);
if (type.equals(Date.class.getName())) {
return readOnly ? new TextView(context) : new EditText(context);
}
return null;
}
}
| package todomore.android.metawidget;
import java.util.Map;
import org.metawidget.android.widget.AndroidMetawidget;
import org.metawidget.widgetbuilder.iface.WidgetBuilder;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TodoMoreAndroidWidgetBuilder implements WidgetBuilder<View, AndroidMetawidget> {
private static final String TAG = "TAWB";
public TodoMoreAndroidWidgetBuilder() {
Log.d(TAG, "TodoAndroidWidgetBuilder()");
// empty
}
@Override
public View buildWidget(String elementName,
Map<String, String> attributes,
AndroidMetawidget metaWidget) {
// Log.d(TAG, String.format("buildWidget(%s, %s, %s)", elementName, attributes, metaWidget));
Context context = metaWidget.getContext();
String type = attributes.get("type");
String readOnlyStr = attributes.get("read-only");
boolean readOnly = Boolean.parseBoolean(readOnlyStr);
if (elementName.equals("entity") && type.equals("com.darwinsys.todo.model.Date")) {
return readOnly ? new TextView(context) : new EditText(context);
}
return null;
}
}
|
Fix potential unicode issues with Like.__unicode__() | from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
# Compatibility with custom user models, while keeping backwards-compatibility with <1.5
AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User")
class Like(models.Model):
sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking")
receiver_content_type = models.ForeignKey(ContentType)
receiver_object_id = models.PositiveIntegerField()
receiver = generic.GenericForeignKey(
ct_field="receiver_content_type",
fk_field="receiver_object_id"
)
timestamp = models.DateTimeField(default=timezone.now)
class Meta:
unique_together = (
("sender", "receiver_content_type", "receiver_object_id"),
)
def __unicode__(self):
return u"%s likes %s" % (self.sender, self.receiver)
| from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
# Compatibility with custom user models, while keeping backwards-compatibility with <1.5
AUTH_USER_MODEL = getattr(settings, "AUTH_USER_MODEL", "auth.User")
class Like(models.Model):
sender = models.ForeignKey(AUTH_USER_MODEL, related_name="liking")
receiver_content_type = models.ForeignKey(ContentType)
receiver_object_id = models.PositiveIntegerField()
receiver = generic.GenericForeignKey(
ct_field="receiver_content_type",
fk_field="receiver_object_id"
)
timestamp = models.DateTimeField(default=timezone.now)
class Meta:
unique_together = (
("sender", "receiver_content_type", "receiver_object_id"),
)
def __unicode__(self):
return "%s likes %s" % (self.sender, self.receiver)
|
Fix pylint errors that snuck into 2015.2 | # -*- coding: utf-8 -*-
'''
A Runner module interface on top of the salt-ssh Python API.
This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc.
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Libs
import salt.client.ssh.client
def cmd(
tgt,
fun,
arg=(),
timeout=None,
expr_form='glob',
kwarg=None):
'''
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionaddedd:: 2015.2
A wrapper around the :py:meth:`SSHClient.cmd
<salt.client.ssh.client.SSHClient.cmd>` method.
'''
client = salt.client.ssh.client.SSHClient(mopts=__opts__)
return client.cmd(
tgt,
fun,
arg,
timeout,
expr_form,
kwarg)
| # utf-8
'''
A Runner module interface on top of the salt-ssh Python API
This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc.
'''
import salt.client.ssh.client
def cmd(
tgt,
fun,
arg=(),
timeout=None,
expr_form='glob',
kwarg=None):
'''
Execute a single command via the salt-ssh subsystem and return all
routines at once
.. versionaddedd:: 2015.2
A wrapper around the :py:meth:`SSHClient.cmd
<salt.client.ssh.client.SSHClient.cmd>` method.
'''
client = salt.client.ssh.client.SSHClient(mopts=__opts__)
return client.cmd(
tgt,
fun,
arg,
timeout,
expr_form,
kwarg)
|
Add cidata to the list of restricted projects | RESTRICTED_PROJECTS = [
'cidata',
'dubtestproject',
'meson',
'meson-ci',
'mesonbuild.github.io',
'mesonwrap',
'wrapdb',
'wrapdevtools',
'wrapweb',
]
ISSUE_TRACKER = 'wrapdb'
class Inventory:
def __init__(self, organization):
self.organization = organization
self.restricted_projects = [
organization + '/' + proj for proj in RESTRICTED_PROJECTS
]
self.issue_tracker = organization + '/' + ISSUE_TRACKER
DEFAULT = Inventory('mesonbuild')
def is_wrap_project_name(project: str) -> bool:
return project not in RESTRICTED_PROJECTS
def is_wrap_full_project_name(full_project: str) -> bool:
return full_project not in DEFAULT.restricted_projects
| RESTRICTED_PROJECTS = [
'dubtestproject',
'meson',
'meson-ci',
'mesonbuild.github.io',
'mesonwrap',
'wrapdb',
'wrapdevtools',
'wrapweb',
]
ISSUE_TRACKER = 'wrapdb'
class Inventory:
def __init__(self, organization):
self.organization = organization
self.restricted_projects = [
organization + '/' + proj for proj in RESTRICTED_PROJECTS
]
self.issue_tracker = organization + '/' + ISSUE_TRACKER
DEFAULT = Inventory('mesonbuild')
def is_wrap_project_name(project: str) -> bool:
return project not in RESTRICTED_PROJECTS
def is_wrap_full_project_name(full_project: str) -> bool:
return full_project not in DEFAULT.restricted_projects
|
Remove SSL warning on CC image | <?php
/**
* The template for displaying the footer
*
* Contains footer content and the closing of the #main and #page div elements.
*
* @package WordPress
* @subpackage Twenty_Fourteen
* @since Twenty Fourteen 1.0
*/
?>
</div><!-- #main -->
<footer id="colophon" class="site-footer" role="contentinfo">
<?php get_sidebar( 'footer' ); ?>
<div class="site-info">
<?php do_action( 'twentyfourteen_credits' ); ?>
<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'twentyfourteen' ) ); ?>"><?php printf( __( 'Proudly powered by %s', 'twentyfourteen' ), 'WordPress' ); ?></a>
<a class="license" rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Licensed under <img alt="Creative Commons License" style="border-width:0" src="//i.creativecommons.org/l/by-nc-sa/4.0/80x15.png" /></a>
</div><!-- .site-info -->
</footer><!-- #colophon -->
</div><!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
| <?php
/**
* The template for displaying the footer
*
* Contains footer content and the closing of the #main and #page div elements.
*
* @package WordPress
* @subpackage Twenty_Fourteen
* @since Twenty Fourteen 1.0
*/
?>
</div><!-- #main -->
<footer id="colophon" class="site-footer" role="contentinfo">
<?php get_sidebar( 'footer' ); ?>
<div class="site-info">
<?php do_action( 'twentyfourteen_credits' ); ?>
<a href="<?php echo esc_url( __( 'http://wordpress.org/', 'twentyfourteen' ) ); ?>"><?php printf( __( 'Proudly powered by %s', 'twentyfourteen' ), 'WordPress' ); ?></a>
<a class="license" rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Licensed under <img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-sa/4.0/80x15.png" /></a>
</div><!-- .site-info -->
</footer><!-- #colophon -->
</div><!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
|
Fix assertInternalType deprecation in phpunit 9 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Tests;
use Symfony\Bridge\PhpUnit\ForwardCompatTestTrait;
use Symfony\Contracts\HttpClient\Test\HttpClientTestCase as BaseHttpClientTestCase;
abstract class HttpClientTestCase extends BaseHttpClientTestCase
{
use ForwardCompatTestTrait;
public function testToStream()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057');
$stream = $response->toStream();
$this->assertSame("{\n \"SER", fread($stream, 10));
$this->assertSame('VER_PROTOCOL', fread($stream, 12));
$this->assertFalse(feof($stream));
$this->assertTrue(rewind($stream));
$this->assertIsArray(json_decode(fread($stream, 1024), true));
$this->assertSame('', fread($stream, 1));
$this->assertTrue(feof($stream));
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Tests;
use Symfony\Contracts\HttpClient\Test\HttpClientTestCase as BaseHttpClientTestCase;
abstract class HttpClientTestCase extends BaseHttpClientTestCase
{
public function testToStream()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057');
$stream = $response->toStream();
$this->assertSame("{\n \"SER", fread($stream, 10));
$this->assertSame('VER_PROTOCOL', fread($stream, 12));
$this->assertFalse(feof($stream));
$this->assertTrue(rewind($stream));
$this->assertInternalType('array', json_decode(fread($stream, 1024), true));
$this->assertSame('', fread($stream, 1));
$this->assertTrue(feof($stream));
}
}
|
Fix hash tag linking entities | from django import template
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import re
import urllib
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
hashtag_re = re.compile('\b#[^\s]+')
@register.filter
def buglise(s):
s = unicode(s)
usernames = set(User.objects.values_list('username', flat=True))
def replace_username(match):
username = match.group(0)[1:]
if username.lower() == 'all':
return '<strong>@all</strong>'
if username in usernames:
return '<a href="/%s/">@%s</a>' % (username, username)
else:
return '@' + username
s = username_re.sub(replace_username, s)
s = hashtag_re.sub(
lambda m: '<a href="/search/?q=%s">%s</a>' % (
urllib.quote(m.group(0)),
m.group(0),
),
s
)
return mark_safe(s)
| from django import template
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
import re
import urllib
register = template.Library()
username_re = re.compile('@[0-9a-zA-Z]+')
hashtag_re = re.compile('#[^\s]+')
@register.filter
def buglise(s):
s = unicode(s)
usernames = set(User.objects.values_list('username', flat=True))
def replace_username(match):
username = match.group(0)[1:]
if username.lower() == 'all':
return '<strong>@all</strong>'
if username in usernames:
return '<a href="/%s/">@%s</a>' % (username, username)
else:
return '@' + username
s = username_re.sub(replace_username, s)
s = hashtag_re.sub(
lambda m: '<a href="/search/?q=%s">%s</a>' % (
urllib.quote(m.group(0)),
m.group(0),
),
s
)
return mark_safe(s)
|
Support ES5
Added isEmptyObject method | var _ = require('underscore');
_.mixin({
offset: function (arr, offset, length) {
var newArr = [];
for (var i = offset; i < offset + length; i++) {
if (!arr[i]) break;
newArr.push(arr[i]);
}
return newArr;
},
iintersection: function (array) {
var rest = _.rest(arguments);
array = _.map(array, (item) => {
return _.isString(item) ? item.toLowerCase() : item;
});
return _.filter(_.uniq(array), function (item) {
return _.every(rest, function (other) {
other = _.map(other, (item) => {
return _.isString(item) ? item.toLowerCase() : item;
});
return _.indexOf(other, item) >= 0;
});
});
},
isEmptyObject: function (obj) {
return _.keys(obj).length === 0;
}
}); | import _ from 'underscore'
_.mixin({
offset: function (arr, offset, length) {
let newArr = [];
for (let i = offset; i < offset + length; i++) {
if (!arr[i]) break;
newArr.push(arr[i]);
}
return newArr;
},
iintersection: function (array, ...rest) {
array = _.map(array, (item) => {
return _.isString(item) ? item.toLowerCase() : item;
});
return _.filter(_.uniq(array), function (item) {
return _.every(rest, function (other) {
other = _.map(other, (item) => {
return _.isString(item) ? item.toLowerCase() : item;
});
return _.indexOf(other, item) >= 0;
});
});
}
}); |
Allow setting the templateCache exported filename | // CI: Angular - Template Cache.js
// ---
// Create a template cache for AngularJS Projects
var gulp = require("gulp");
var gUtil = require("gulp-util");
var templateCache = require("gulp-angular-templatecache");
// Load the build configuration
var config = require("./../config/config.json");
gulp.task("angular:template-cache", function() {
// Globbing patterns
var patterns = [
config.env.dev.scripts.dir + "app/**/*.html"
];
// TemplateCache options
var options = {};
if (config["template-cache"]) {
options = {
filename: config["template-cache"].filename || "app.templates.js",
module: config["template-cache"].module
};
} else {
gUtil.log("No angular-template-cache configuration was found. This might be an error, so we\'re letting you know ;-).");
}
var destination = config.env.dev.scripts.dir + "app/";
return gulp.src(patterns)
.pipe(templateCache(options))
.pipe(gulp.dest(destination));
});
| // CI: Angular - Template Cache.js
// ---
// Create a template cache for AngularJS Projects
var gulp = require("gulp");
var gUtil = require("gulp-util");
var templateCache = require("gulp-angular-templatecache");
// Load the build configuration
var config = require("./../config/config.json");
gulp.task("angular:template-cache", function() {
// Globbing patterns
var patterns = [
config.env.dev.serve.dir + "app/**/*.html"
];
// TemplateCache options
var options = {};
if (config["template-cache"]) {
options = {
module: config["template-cache"].module
};
} else {
gUtil.log("No angular-template-cache configuration was found. This might be an error, so we\'re letting you know ;-).");
}
var destination = config.env.dev.serve.dir + "app/";
return gulp.src(patterns)
.pipe(templateCache(options))
.pipe(gulp.dest(destination));
});
|
Use route name instead of route path | import Ember from 'ember';
var inject = Ember.inject;
export default Ember.Route.extend({
searchQuery: inject.service(),
history: inject.service(),
beforeModel: function(transition) {
// capture the first page load
this.get('history').capture(transition);
},
actions: {
willTransition: function(transition) {
this.get('history').capture(transition);
},
goBack: function() {
var previousTransition = this.get('history.previous');
if (previousTransition) {
this.get('history').capture(previousTransition);
previousTransition.retry();
} else {
this.transitionTo('home');
}
},
search: function() {
var params = { query: this.get('searchQuery.value') };
this.transitionTo('stops.search', { queryParams: params });
},
error: function(error) {
switch (error.errorThrown) {
case "Not Found":
this.transitionTo('404');
break;
default:
this.transitionTo('500');
}
}
}
});
| import Ember from 'ember';
var inject = Ember.inject;
export default Ember.Route.extend({
searchQuery: inject.service(),
history: inject.service(),
beforeModel: function(transition) {
// capture the first page load
this.get('history').capture(transition);
},
actions: {
willTransition: function(transition) {
this.get('history').capture(transition);
},
goBack: function() {
var previousTransition = this.get('history.previous');
if (previousTransition) {
this.get('history').capture(previousTransition);
previousTransition.retry();
} else {
this.transitionTo('home');
}
},
search: function() {
var params = { query: this.get('searchQuery.value') };
this.transitionTo('stops.search', { queryParams: params });
},
error: function(error) {
switch (error.errorThrown) {
case "Not Found":
this.transitionTo('/404');
break;
default:
this.transitionTo('/500');
}
}
}
});
|
Return back separator for Morden since wrong forked peers are still there | package org.ethereum.config.net;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.blockchain.Eip150HFConfig;
import org.ethereum.config.blockchain.Eip160HFConfig;
import org.ethereum.config.blockchain.MordenConfig;
import org.spongycastle.util.encoders.Hex;
import java.util.Collections;
import java.util.List;
/**
* Created by Anton Nashatyrev on 25.02.2016.
*/
public class MordenNetConfig extends AbstractNetConfig {
private static final long EIP150_HF_BLOCK = 1_783_000;
private static final byte[] EIP150_HF_BLOCK_HASH =
Hex.decode("f376243aeff1f256d970714c3de9fd78fa4e63cf63e32a51fe1169e375d98145");
public MordenNetConfig() {
add(0, new MordenConfig.Frontier());
add(494_000, new MordenConfig.Homestead());
add(EIP150_HF_BLOCK, new Eip150HFConfig(new MordenConfig.Homestead()) {
@Override
public List<Pair<Long, byte[]>> blockHashConstraints() {
return Collections.singletonList(Pair.of(EIP150_HF_BLOCK, EIP150_HF_BLOCK_HASH));
}
});
add(1_885_000, new Eip160HFConfig(new MordenConfig.Homestead()));
}
}
| package org.ethereum.config.net;
import org.apache.commons.lang3.tuple.Pair;
import org.ethereum.config.blockchain.DaoHFConfig;
import org.ethereum.config.blockchain.Eip150HFConfig;
import org.ethereum.config.blockchain.Eip160HFConfig;
import org.ethereum.config.blockchain.MordenConfig;
import org.spongycastle.util.encoders.Hex;
import java.util.Collections;
import java.util.List;
/**
* Created by Anton Nashatyrev on 25.02.2016.
*/
public class MordenNetConfig extends AbstractNetConfig {
public MordenNetConfig() {
add(0, new MordenConfig.Frontier());
add(494_000, new MordenConfig.Homestead());
add(1_783_000, new Eip150HFConfig(new MordenConfig.Homestead()));
add(1_885_000, new Eip160HFConfig(new MordenConfig.Homestead()));
}
}
|
Fix was_published_recently reporting polls from the future | from django.db import models
from django.utils import timezone
from datetime import timedelta
class Poll(models.Model):
text = models.CharField(max_length=200)
created_ts = models.DateTimeField()
updated_ts = models.DateTimeField(null=True, default=None)
is_published = models.BooleanField(default=False)
publication_date = models.DateTimeField(
'date published',
default=None,
)
def __str__(self):
return self.text
def was_published_recently(self):
now = timezone.now()
return now - timedelta(days=1) <= self.publication_date <= now
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created_ts = timezone.now()
self.updated_ts = timezone.now()
return super(Poll, self).save(*args, **kwargs)
class Choice(models.Model):
poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.text
| from django.db import models
from django.utils import timezone
from datetime import timedelta
class Poll(models.Model):
text = models.CharField(max_length=200)
created_ts = models.DateTimeField()
updated_ts = models.DateTimeField(null=True, default=None)
is_published = models.BooleanField(default=False)
publication_date = models.DateTimeField(
'date published',
default=None,
)
def __str__(self):
return self.text
def was_published_recently(self):
return self.publication_date >= timezone.now() - timedelta(days=1)
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created_ts = timezone.now()
self.updated_ts = timezone.now()
return super(Poll, self).save(*args, **kwargs)
class Choice(models.Model):
poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.text
|
Fix Bin2hex: the length has to include the trailing \0 | package sodium
import "fmt"
import "unsafe"
// #include <stdio.h>
// #include <sodium.h>
import "C"
func MemZero(buff1 []byte) {
if len(buff1) > 0 {
C.sodium_memzero(unsafe.Pointer(&buff1[0]), C.size_t(len(buff1)))
}
}
func MemCmp(buff1, buff2 []byte, length int) int {
if length >= len(buff1) || length >= len(buff2) {
panic(fmt.Sprintf("Attempt to compare more bytes (%d) than provided " +
"(%d, %d)", length, len(buff1), len(buff2)))
}
return int(C.sodium_memcmp(unsafe.Pointer(&buff1[0]),
unsafe.Pointer(&buff2[0]),
C.size_t(length)))
}
func Bin2hex(bin []byte) string {
maxlen := len(bin) * 2 + 1
binPtr := (*C.uchar)(unsafe.Pointer(&bin[0]))
buf := (*C.char)(C.malloc(C.size_t(maxlen)))
defer C.free(unsafe.Pointer(buf))
C.sodium_bin2hex(buf, C.size_t(maxlen), binPtr, C.size_t(len(bin)))
return C.GoString(buf)
}
| package sodium
import "fmt"
import "unsafe"
// #include <stdio.h>
// #include <sodium.h>
import "C"
func MemZero(buff1 []byte) {
if len(buff1) > 0 {
C.sodium_memzero(unsafe.Pointer(&buff1[0]), C.size_t(len(buff1)))
}
}
func MemCmp(buff1, buff2 []byte, length int) int {
if length >= len(buff1) || length >= len(buff2) {
panic(fmt.Sprintf("Attempt to compare more bytes (%d) than provided " +
"(%d, %d)", length, len(buff1), len(buff2)))
}
return int(C.sodium_memcmp(unsafe.Pointer(&buff1[0]),
unsafe.Pointer(&buff2[0]),
C.size_t(length)))
}
func Bin2hex(bin []byte) string {
maxlen := len(bin) * 2
binPtr := (*C.uchar)(unsafe.Pointer(&bin[0]))
buf := (*C.char)(C.malloc(C.size_t(maxlen)))
defer C.free(unsafe.Pointer(buf))
C.sodium_bin2hex(buf, C.size_t(maxlen), binPtr, C.size_t(len(bin)))
return C.GoString(buf)
}
|
Add generic full board display message method
Currently used successfully by high score win | var DisplayLeaderboard = require('./display-leaderboard');
const templates = require('./message-templates');
const $ = require('jquery');
function DisplayMessage(){
this.element = $('#post-game');
}
DisplayMessage.prototype.showBoardMessage = function(template) {
var div = this.element;
div.empty()
.show()
.append(template);
};
DisplayMessage.prototype.showWinMessage = function(){
var div = this.element;
div.empty()
.show()
.append(`<h1>You Win!</h1>
<p>Click to play the next level.</p>`
);
div.on('click', function(){
div.hide();
});
};
DisplayMessage.prototype.showHighScoreMessage = function(game, leaderboard){
this.showBoardMessage(templates.highScoreWin);
div.unbind('click').on('click', 'button', function() {
var input = $('.input').val();
game.getName(input, leaderboard);
if(leaderboard.name === 'Level Random'){
new DisplayLeaderboard(leaderboard);
}
div.hide();
});
};
DisplayMessage.prototype.showScore = function(score){
$('#score').empty().append(this.scoreElement(score));
};
DisplayMessage.prototype.scoreElement = function(score){
return '<h1>Score: ' + score + '</h1>';
};
module.exports = DisplayMessage;
| var DisplayLeaderboard = require('./display-leaderboard');
const $ = require('jquery');
function DisplayMessage(){
this.element = $('#post-game');
}
DisplayMessage.prototype.showWinMessage = function(){
var div = this.element;
div.empty()
.show()
.append(`<h1>You Win!</h1>
<p>Click to play the next level.</p>`
);
div.on('click', function(){
div.hide();
});
};
DisplayMessage.prototype.showHighScoreMessage = function(game, leaderboard){
var div = this.element;
div.empty()
.show()
.append(`<h1>High Score!</h1>
<p>Name:</p>
<input class='input'></input>
<button id="high-submit-button">Submit</button>`
);
div.unbind('click').on('click', 'button', function() {
var input = $('.input').val();
game.getName(input, leaderboard);
if(leaderboard.name === 'Level Random'){
new DisplayLeaderboard(leaderboard);
}
div.hide();
});
};
DisplayMessage.prototype.showScore = function(score){
$('#score').empty().append(this.scoreElement(score));
};
DisplayMessage.prototype.scoreElement = function(score){
return '<h1>Score: ' + score + '</h1>';
};
module.exports = DisplayMessage;
|
Adjust migrate console controller to use a new migration template view file. | <?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'controllerMap' => [
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'templateFile' => '@console/views/migration.php',
],
],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params,
];
| <?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params,
];
|
Test that the registry's root has a null parent | # Pytest will pick up this module automatically when running just "pytest".
#
# Each test_*() function gets passed test fixtures, which are defined
# in conftest.py. So, a function "def test_foo(bar)" will get a bar()
# fixture created for it.
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties'
ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible'
def get_property(proxy, iface_name, prop_name):
return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE)
def test_accessible_iface_properties(registry, session_manager):
values = [
('Name', 'main'),
('Description', ''),
]
for prop_name, expected in values:
assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected
def test_registry_root_has_null_parent(registry, session_manager):
assert get_property(registry, ACCESSIBLE_IFACE, 'Parent') == ('', '/org/a11y/atspi/null')
def test_empty_registry_has_zero_children(registry, session_manager):
assert get_property(registry, ACCESSIBLE_IFACE, 'ChildCount') == 0
| # Pytest will pick up this module automatically when running just "pytest".
#
# Each test_*() function gets passed test fixtures, which are defined
# in conftest.py. So, a function "def test_foo(bar)" will get a bar()
# fixture created for it.
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties'
ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible'
def get_property(proxy, iface_name, prop_name):
return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE)
def test_accessible_iface_properties(registry, session_manager):
values = [
('Name', 'main'),
('Description', ''),
]
for prop_name, expected in values:
assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected
def test_empty_registry_has_zero_children(registry, session_manager):
assert get_property(registry, ACCESSIBLE_IFACE, 'ChildCount') == 0
|
Fix reset password for MyGFW | import { createThunkAction } from 'utils/redux';
import { FORM_ERROR } from 'final-form';
import { login, register, resetPassword } from 'services/user';
import { getUserProfile } from 'providers/mygfw-provider/actions';
export const loginUser = createThunkAction('logUserIn', data => dispatch =>
login(data)
.then(response => {
if (response.status < 400 && response.data) {
dispatch(getUserProfile());
}
})
.catch(error => {
const { errors } = error.response.data;
return {
[FORM_ERROR]: errors[0].detail
};
})
);
export const registerUser = createThunkAction('sendRegisterUser', data => () =>
register(data)
.then(() => {})
.catch(error => {
const { errors } = error.response.data;
return {
[FORM_ERROR]: errors[0].detail
};
})
);
export const resetUserPassword = createThunkAction(
'sendResetPassword',
data => () =>
resetPassword(data)
.then(() => {})
.catch(error => {
const { errors } = error.response.data;
return {
[FORM_ERROR]: errors[0].detail
};
})
);
| import { createThunkAction } from 'utils/redux';
import { FORM_ERROR } from 'final-form';
import { login, register, resetPassword } from 'services/user';
import { getUserProfile } from 'providers/mygfw-provider/actions';
export const loginUser = createThunkAction('logUserIn', data => dispatch =>
login(data)
.then(response => {
if (response.status < 400 && response.data) {
dispatch(getUserProfile());
}
})
.catch(error => {
const { errors } = error.response.data;
return {
[FORM_ERROR]: errors[0].detail
};
})
);
export const registerUser = createThunkAction('sendRegisterUser', data => () =>
register(data)
.then(() => {})
.catch(error => {
const { errors } = error.response.data;
return {
[FORM_ERROR]: errors[0].detail
};
})
);
export const resetUserPassword = createThunkAction(
'sendResetPassword',
({ data, success }) => () =>
resetPassword(data)
.then(() => {
success();
})
.catch(error => {
const { errors } = error.response.data;
return {
[FORM_ERROR]: errors[0].detail
};
})
);
|
Add model for certificate signing request (CSR)
Clean out view/db_init code from scaffold.
Replace routes from scaffold.
Add pyOpenSSL dependancy to setup.py. | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, "README.txt")).read()
CHANGES = open(os.path.join(here, "CHANGES.txt")).read()
requires = [
"pyramid",
"SQLAlchemy",
"transaction",
"pyramid_tm",
"pyramid_debugtoolbar",
"zope.sqlalchemy",
"waitress",
"pyOpenSSL"
]
setup(name="caramel",
version="0.0",
description="caramel",
long_description=README + "\n\n" + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pyramid",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author="",
author_email="",
url="",
keywords="web wsgi bfg pylons pyramid",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
test_suite="caramel",
install_requires=requires,
entry_points="""\
[paste.app_factory]
main = caramel:main
[console_scripts]
initialize_caramel_db = caramel.scripts.initializedb:main
""",
)
| import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, "README.txt")).read()
CHANGES = open(os.path.join(here, "CHANGES.txt")).read()
requires = [
"pyramid",
"SQLAlchemy",
"transaction",
"pyramid_tm",
"pyramid_debugtoolbar",
"zope.sqlalchemy",
"waitress",
]
setup(name="caramel",
version="0.0",
description="caramel",
long_description=README + "\n\n" + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pyramid",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author="",
author_email="",
url="",
keywords="web wsgi bfg pylons pyramid",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
test_suite="caramel",
install_requires=requires,
entry_points="""\
[paste.app_factory]
main = caramel:main
[console_scripts]
initialize_caramel_db = caramel.scripts.initializedb:main
""",
)
|
Update internal version variable to 0.1.2 | function Rye (selector, context) {
if (!(this instanceof Rye)){
return new Rye(selector, context)
}
if (selector instanceof Rye){
return selector
}
var util = Rye.require('Util')
if (typeof selector === 'string') {
this.selector = selector
this.elements = this.qsa(context, selector)
} else if (selector instanceof Array) {
this.elements = util.unique(selector.filter(util.isElement))
} else if (util.isNodeList(selector)) {
this.elements = Array.prototype.slice.call(selector).filter(util.isElement)
} else if (util.isElement(selector)) {
this.elements = [selector]
} else {
this.elements = []
}
this._update()
}
Rye.version = '0.1.2'
// Minimalist module system
Rye._modules = {}
Rye.require = function (module) {
return Rye._modules[module]
}
Rye.define = function (module, fn) {
Rye._modules[module] = fn.call(Rye.prototype)
}
| function Rye (selector, context) {
if (!(this instanceof Rye)){
return new Rye(selector, context)
}
if (selector instanceof Rye){
return selector
}
var util = Rye.require('Util')
if (typeof selector === 'string') {
this.selector = selector
this.elements = this.qsa(context, selector)
} else if (selector instanceof Array) {
this.elements = util.unique(selector.filter(util.isElement))
} else if (util.isNodeList(selector)) {
this.elements = Array.prototype.slice.call(selector).filter(util.isElement)
} else if (util.isElement(selector)) {
this.elements = [selector]
} else {
this.elements = []
}
this._update()
}
Rye.version = '0.1.0'
// Minimalist module system
Rye._modules = {}
Rye.require = function (module) {
return Rye._modules[module]
}
Rye.define = function (module, fn) {
Rye._modules[module] = fn.call(Rye.prototype)
}
|
Change Runable function to RunableB | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.lomatek.jslint;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import org.openide.loaders.DataObject;
import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.openide.util.NbBundle.Messages;
import org.openide.util.RequestProcessor;
@ActionID(category = "Build",
id = "org.lomatek.jslint.JSLintSample")
@ActionRegistration(displayName = "#CTL_JSLintSample")
@ActionReferences({
@ActionReference(path = "Editors/text/javascript/Popup", position = 300)
})
@Messages("CTL_JSLintSample=JSLintSample")
public final class JSLintSample implements ActionListener {
static RequestProcessor processor = null;
private final DataObject context;
public JSLintSample(DataObject context) {
this.context = context;
}
public void actionPerformed(ActionEvent ev) {
// TODO use context
if (processor == null) {
processor = new RequestProcessor("TidyErrorCheck", 1, true);
}
processor.post(new JSLintRunnableB(context, "-e"));
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.lomatek.jslint;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import org.openide.loaders.DataObject;
import org.openide.awt.ActionRegistration;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionID;
import org.openide.util.NbBundle.Messages;
import org.openide.util.RequestProcessor;
@ActionID(category = "Build",
id = "org.lomatek.jslint.JSLintSample")
@ActionRegistration(displayName = "#CTL_JSLintSample")
@ActionReferences({
@ActionReference(path = "Editors/text/javascript/Popup", position = 300)
})
@Messages("CTL_JSLintSample=JSLintSample")
public final class JSLintSample implements ActionListener {
static RequestProcessor processor = null;
private final DataObject context;
public JSLintSample(DataObject context) {
this.context = context;
}
public void actionPerformed(ActionEvent ev) {
// TODO use context
if (processor == null) {
processor = new RequestProcessor("TidyErrorCheck", 1, true);
}
processor.post(new JSLintRunnable(context, "-e"));
}
}
|
Make use of yii::t() on buttons text | <?php
use yii\helpers\Url;
/* @var $this yii\web\View */
$this->title = 'Articles';
?>
<h2>
<a href=<?= Url::to(['article/view', 'id' => $model->id]) ?>><?= $model->title ?></a>
</h2>
<p class="time"><span class="glyphicon glyphicon-time"></span>
<?= Yii::t('app','Published on').' '.date('F j, Y, g:i a', $model->created_at) ?></p>
<br>
<p><?= $model->summary ?></p>
<a class="btn btn-primary" href=<?= Url::to(['article/view', 'id' => $model->id]) ?>>
<?= yii::t('app','Read more'); ?><span class="glyphicon glyphicon-chevron-right"></span>
</a>
<hr class="article-devider">
| <?php
use yii\helpers\Url;
/* @var $this yii\web\View */
$this->title = 'Articles';
?>
<h2>
<a href=<?= Url::to(['article/view', 'id' => $model->id]) ?>><?= $model->title ?></a>
</h2>
<p class="time"><span class="glyphicon glyphicon-time"></span>
Published on <?= date('F j, Y, g:i a', $model->created_at) ?></p>
<br>
<p><?= $model->summary ?></p>
<a class="btn btn-primary" href=<?= Url::to(['article/view', 'id' => $model->id]) ?>>
Read More <span class="glyphicon glyphicon-chevron-right"></span>
</a>
<hr class="article-devider">
|
Remove print. Tag should be made before publish. | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
from setuptools import setup
from pathlib import Path
this_dir = Path(__file__).absolute().parent
if sys.argv[-1].startswith('publish'):
if os.system("pip list | grep wheel"):
print("wheel not installed.\nUse `pip install wheel`.\nExiting.")
sys.exit()
if os.system("pip list | grep twine"):
print("twine not installed.\nUse `pip install twine`.\nExiting.")
sys.exit()
os.system("python setup.py sdist bdist_wheel")
if sys.argv[-1] == 'publishtest':
os.system("twine upload -r test dist/*")
else:
os.system("twine upload dist/*")
sys.exit()
if __name__ == "__main__":
setup(use_scm_version={
"write_to": str(this_dir / "parglare" / "version.py"),
"write_to_template": '__version__ = "{version}"\n',
})
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
from setuptools import setup
from pathlib import Path
this_dir = Path(__file__).absolute().parent
if sys.argv[-1].startswith('publish'):
if os.system("pip list | grep wheel"):
print("wheel not installed.\nUse `pip install wheel`.\nExiting.")
sys.exit()
if os.system("pip list | grep twine"):
print("twine not installed.\nUse `pip install twine`.\nExiting.")
sys.exit()
os.system("python setup.py sdist bdist_wheel")
if sys.argv[-1] == 'publishtest':
os.system("twine upload -r test dist/*")
else:
os.system("twine upload dist/*")
print("You probably want to also tag the version now.")
sys.exit()
if __name__ == "__main__":
setup(use_scm_version={
"write_to": str(this_dir / "parglare" / "version.py"),
"write_to_template": '__version__ = "{version}"\n',
})
|
: Create documentation of DataSource Settings
Task-Url: | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.show( t1 )
print '\n\n'
AdminConfig.showall( t1 )
AdminConfig.showAttribute(t1,'[[statementCacheSize]]' ) | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.show( t1 )
print '\n\n'
AdminConfig.showall( t1 ) |
Apply suggested changes on date | from datetime import date, datetime, timedelta
from django.core.exceptions import ValidationError
def validate_approximatedate(date):
if date.month == 0:
raise ValidationError(
'Event date can\'t be a year only. '
'Please, provide at least a month and a year.'
)
def validate_event_date(e_date):
today = date.today()
event_date = datetime.date(datetime.strptime('{0}-{1}-{2}'.format(e_date.year, e_date.month, e_date.day),
'%Y-%m-%d'))
if event_date - today < timedelta(days=90):
raise ValidationError('Your event date is too close. '
'Workshop date should be at least 3 months (90 days) from now.')
| from datetime import datetime, timedelta
from django.core.exceptions import ValidationError
def validate_approximatedate(date):
if date.month == 0:
raise ValidationError(
'Event date can\'t be a year only. '
'Please, provide at least a month and a year.'
)
def validate_event_date(date):
today = datetime.today()
event_date = datetime.date(datetime.strptime('{0}-{1}-{2}'.format(date.year, date.month, date.day), '%Y-%m-%d'))
if event_date - datetime.date(today) < timedelta(days=90):
raise ValidationError('Your event date is too close. '
'Workshop date should be at least 3 months (90 days) from now.')
|
Add accessory model to accessories | @extends('layouts/edit-form', [
'createText' => trans('admin/accessories/general.create') ,
'updateText' => trans('admin/accessories/general.update'),
'helpTitle' => trans('admin/accessories/general.about_accessories_title'),
'helpText' => trans('admin/accessories/general.about_accessories_text')
])
{{-- Page content --}}
@section('inputFields')
@include ('partials.forms.edit.company')
@include ('partials.forms.edit.name', ['translated_name' => trans('admin/accessories/general.accessory_name')])
@include ('partials.forms.edit.category')
@include ('partials.forms.edit.manufacturer')
@include ('partials.forms.edit.location')
@include ('partials.forms.edit.model_number')
@include ('partials.forms.edit.order_number')
@include ('partials.forms.edit.purchase_date')
@include ('partials.forms.edit.purchase_cost')
@include ('partials.forms.edit.quantity')
@include ('partials.forms.edit.minimum_quantity')
@stop
| @extends('layouts/edit-form', [
'createText' => trans('admin/accessories/general.create') ,
'updateText' => trans('admin/accessories/general.update'),
'helpTitle' => trans('admin/accessories/general.about_accessories_title'),
'helpText' => trans('admin/accessories/general.about_accessories_text')
])
{{-- Page content --}}
@section('inputFields')
@include ('partials.forms.edit.company')
@include ('partials.forms.edit.name', ['translated_name' => trans('admin/accessories/general.accessory_name')])
@include ('partials.forms.edit.category')
@include ('partials.forms.edit.manufacturer')
@include ('partials.forms.edit.location')
@include ('partials.forms.edit.order_number')
@include ('partials.forms.edit.purchase_date')
@include ('partials.forms.edit.purchase_cost')
@include ('partials.forms.edit.quantity')
@include ('partials.forms.edit.minimum_quantity')
@stop
|
Use .forEach() instead of a for loop for image handling. | var chat = require('../lib/server'),
router = require("../lib/router");
// create chat server and a single channel
var chatServer = chat.createServer();
chatServer.listen(8001);
chatServer.addChannel({ basePath: "/chat" });
// chat app
chatServer.passThru("/", router.staticHandler("index.html"));
// CSS
chatServer.passThru("/css/layout.css", router.staticHandler("css/layout.css"));
chatServer.passThru("/css/reset.css", router.staticHandler("css/reset.css"));
// Images
["background.png", "button.png", "footer.png", "glows.png", "header-bg.png",
"inset-border-l.png", "inset-border.png", "metal.jpg", "node-chat.png",
"send.png"].forEach(function(file) {
chatServer.passThru("/images/" + file, router.staticHandler("images/" + file));
});
// JS
chatServer.passThru("/jquery-1.4.2.js", router.staticHandler("jquery-1.4.2.js"));
chatServer.passThru("/nodechat.js", router.staticHandler("nodechat.js"));
chatServer.passThru("/client.js", router.staticHandler("client.js"));
| var chat = require('../lib/server'),
router = require("../lib/router");
var chatServer = chat.createServer();
chatServer.listen(8001);
chatServer.addChannel({ basePath: "/chat" });
chatServer.passThru("/", router.staticHandler("index.html"));
// CSS
chatServer.passThru("/css/layout.css", router.staticHandler("css/layout.css"));
chatServer.passThru("/css/reset.css", router.staticHandler("css/reset.css"));
// Images
var files = ["background.png", "button.png", "footer.png", "glows.png", "header-bg.png", "inset-border-l.png", "inset-border.png", "metal.jpg","node-chat.png" ,"send.png"];
for (var i = files.length - 1; i >= 0; i--){
chatServer.passThru("/images/" + files[i], router.staticHandler("images/" + files[i]));
};
//
chatServer.passThru("/jquery-1.4.2.js", router.staticHandler("jquery-1.4.2.js"));
chatServer.passThru("/nodechat.js", router.staticHandler("nodechat.js"));
chatServer.passThru("/client.js", router.staticHandler("client.js"));
|
chore(pins): Update dictionary to same pin as API for Horton
- Update dictionary to the same pin as the API uses | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@4a75cc05c7ba2174e70cca9c9ea7e93947f7a868#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@7b5de7d56aa3159a9526940eb273579ddbf084ca#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@6d404dbd1dd45ed35d0aef6d33c43dbbd982930d#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
| from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
package_data={
"gdcdatamodel": [
"xml_mappings/*.yaml",
]
},
dependency_links=[
'git+https://github.com/NCI-GDC/cdisutils.git@4a75cc05c7ba2174e70cca9c9ea7e93947f7a868#egg=cdisutils',
'git+https://github.com/NCI-GDC/psqlgraph.git@7b5de7d56aa3159a9526940eb273579ddbf084ca#egg=psqlgraph',
'git+https://github.com/NCI-GDC/gdcdictionary.git@release/horton#egg=gdcdictionary',
],
entry_points={
'console_scripts': [
'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main'
]
},
)
|
Make sure that tray items is a list
This fixes an exception when tray['items'] is None. The same conditional check is added for response['tray']. | from InstagramAPI.src.http.Response.Objects.Item import Item
from InstagramAPI.src.http.Response.Objects.Tray import Tray
from .Response import Response
class ReelsTrayFeedResponse(Response):
def __init__(self, response):
self.trays = None
if self.STATUS_OK == response['status']:
trays = []
if 'tray' in response and isinstance(response['tray'], list):
for tray in response['tray']:
items = []
if 'items' in tray and isinstance(tray['items'], list):
for item in tray['items']:
items.append(Item(item))
trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at']))
self.trays = trays
else:
self.setMessage(response['message'])
self.setStatus(response['status'])
def getTrays(self):
return self.trays
| from InstagramAPI.src.http.Response.Objects.Item import Item
from InstagramAPI.src.http.Response.Objects.Tray import Tray
from .Response import Response
class ReelsTrayFeedResponse(Response):
def __init__(self, response):
self.trays = None
if self.STATUS_OK == response['status']:
trays = []
if 'tray' in response and len(response['tray']):
for tray in response['tray']:
items = []
if 'items' in tray and len(tray['items']):
for item in tray['items']:
items.append(Item(item))
trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at']))
self.trays = trays
else:
self.setMessage(response['message'])
self.setStatus(response['status'])
def getTrays(self):
return self.trays
|
Fix filter bug on nits | exercism.views.SelectFilter = Backbone.View.extend({
el: $('#pending-submissions'),
events: {
"click #filter-nits": "nitHandler",
"click #filter-opinions": "opinionHandler",
},
initialize: function(options) {
this.listenTo(this.model, "change", this.render);
},
filterNits: function () {
if (this.model.get('nits')) { this.$('div[data-nits][data-nits!=0]').hide(); }
},
filterOpinions: function () {
if (this.model.get('opinions')) { this.$('div[data-opinions][data-opinions!=1]').hide(); }
},
showAll: function () {
this.$('.pending-submission').show();
},
render: function () {
this.showAll();
this.filterNits();
this.filterOpinions();
},
nitHandler: function (event) {
this.model.set("nits", $(event.currentTarget).is(':checked'));
},
opinionHandler: function (event) {
this.model.set("opinions", $(event.currentTarget).is(':checked'));
},
});
| exercism.views.SelectFilter = Backbone.View.extend({
el: $('#pending-submissions'),
events: {
"click #filter-nits": "nitHandler",
"click #filter-opinions": "opinionHandler",
},
initialize: function(options) {
this.listenTo(this.model, "change", this.render);
},
filterNits: function () {
this.$('div[data-nits][data-nits!=0]').toggle(!this.model.get("nits"));
},
filterOpinions: function () {
this.$('div[data-opinions][data-opinions!=1]').toggle(!this.model.get("opinions"));
},
showAll: function () {
this.$('.pending-submission').show();
},
render: function () {
this.showAll();
this.filterNits();
this.filterOpinions();
},
nitHandler: function (event) {
this.model.set("nits", $(event.currentTarget).is(':checked'));
},
opinionHandler: function (event) {
this.model.set("opinions", $(event.currentTarget).is(':checked'));
},
});
|
Add debian endpoint as comment to file. | # This file is part of fedmsg.
# Copyright (C) 2012 Red Hat, Inc.
#
# fedmsg is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# fedmsg is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with fedmsg; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors: Ralph Bean <rbean@redhat.com>
#
config = dict(
# This is a dict of possible addresses from which fedmsg can send
# messages. fedmsg.init(...) requires that a 'name' argument be passed
# to it which corresponds with one of the keys in this dict.
endpoints={
# These are here so your local box can listen to the upstream
# infrastructure's bus. Cool, right? :)
"fedora-infrastructure": [
"tcp://hub.fedoraproject.org:9940",
#"tcp://stg.fedoraproject.org:9940",
],
#"debian-infrastructure": [
# "tcp://fedmsg.olasd.eu:9940",
#],
},
)
| # This file is part of fedmsg.
# Copyright (C) 2012 Red Hat, Inc.
#
# fedmsg is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# fedmsg is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with fedmsg; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Authors: Ralph Bean <rbean@redhat.com>
#
config = dict(
# This is a dict of possible addresses from which fedmsg can send
# messages. fedmsg.init(...) requires that a 'name' argument be passed
# to it which corresponds with one of the keys in this dict.
endpoints={
# These are here so your local box can listen to the upstream
# infrastructure's bus. Cool, right? :)
"fedora-infrastructure": [
"tcp://hub.fedoraproject.org:9940",
#"tcp://stg.fedoraproject.org:9940",
],
},
)
|
Add alert message reducer format | import _ from 'lodash';
import {
OPEN_ALERT_MESSAGE,
CLOSE_ALERT_MESSAGE,
} from '../actions/actionTypes';
const initialState = {
show: false,
title: {
th: '',
en: ''
},
messages: {
th: '',
en: '',
},
technical: {
message: '',
code: '',
},
};
const getInitialState = () => ({
...initialState,
});
export default (state = getInitialState(), action) => {
switch (action.type) {
case OPEN_ALERT_MESSAGE:
return {
...state,
show: true,
title: action.data.title,
messages: action.data.messages,
technical: action.data.technical,
};
case CLOSE_ALERT_MESSAGE:
return getInitialState();
default:
return state;
}
};
| import _ from 'lodash';
import {
OPEN_ALERT_MESSAGE,
CLOSE_ALERT_MESSAGE,
} from '../actions/actionTypes';
const initialState = {
show: false,
messages: {
th: '',
en: '',
},
technical: {
message: '',
code: '',
},
};
const getInitialState = () => ({
...initialState,
});
export default (state = getInitialState(), action) => {
switch (action.type) {
case OPEN_ALERT_MESSAGE:
return {
...state,
show: true,
// messages: action.messages,
};
case CLOSE_ALERT_MESSAGE:
return getInitialState();
default:
return state;
}
};
|
Add a test to check the right number of days in 400 year cycles. | from datetime import date as vanilla_date
from calendar_testing import CalendarTest
from calexicon.calendars.other import JulianDayNumber
class TestJulianDayNumber(CalendarTest):
def setUp(self):
self.calendar = JulianDayNumber()
def test_make_date(self):
vd = vanilla_date(2010, 8, 1)
d = self.calendar.from_date(vd)
self.assertIsNotNone(d)
def test_first_date(self):
vd = vanilla_date(1, 1, 1)
d = self.calendar.from_date(vd)
self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)')
def compare_date_and_number(self, year, month, day, number):
vd = vanilla_date(year, month, day)
d = self.calendar.from_date(vd)
self.assertEqual(d.native_representation(), {'day_number': number})
def test_every_400_years(self):
days_in_400_years = 400 * 365 + 97
for i in range(25):
self.compare_date_and_number(1 + 400 * i, 1, 1, 1721423 + days_in_400_years * i)
def test_another_date(self):
self.compare_date_and_number(2013, 1, 1, 2456293)
| from datetime import date as vanilla_date
from calendar_testing import CalendarTest
from calexicon.calendars.other import JulianDayNumber
class TestJulianDayNumber(CalendarTest):
def setUp(self):
self.calendar = JulianDayNumber()
def test_make_date(self):
vd = vanilla_date(2010, 8, 1)
d = self.calendar.from_date(vd)
self.assertIsNotNone(d)
def test_first_date(self):
vd = vanilla_date(1, 1, 1)
d = self.calendar.from_date(vd)
self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)')
def compare_date_and_number(self, year, month, day, number):
vd = vanilla_date(year, month, day)
d = self.calendar.from_date(vd)
self.assertEqual(d.native_representation(), {'day_number': number})
def test_other_date(self):
self.compare_date_and_number(2013, 1, 1, 2456293)
|
chore(Collective): Add event and events to blacklisted slugs | export const collectiveSlugBlacklist = [
'about',
'admin',
'applications',
'become-a-sponsor',
'chapters',
'collective',
'contact',
'contribute',
'create',
'create-account',
'discover',
'donate',
'edit',
'expenses',
'event',
'events',
'faq',
'gift-card',
'gift-cards',
'gift-cards-next',
'gift-of-giving',
'help',
'home',
'host',
'hosts',
'how-it-works',
'join',
'join-free',
'learn-more',
'order',
'orders',
'pledge',
'pledges',
'privacypolicy',
'redeem',
'redeemed',
'register',
'search',
'signin',
'signup',
'subscriptions',
'tos',
'transactions',
'widgets',
];
/**
* Check if given `slug` could conflict with existing routes or
* if it's a reserved keyword.
*
* The list is mostly based on frontend `src/server/pages.js` file and
* `src/pages/static` content.
*
* @param {String} slug
*/
export function isBlacklistedCollectiveSlug(slug) {
return collectiveSlugBlacklist.includes(slug);
}
| export const collectiveSlugBlacklist = [
'about',
'admin',
'applications',
'become-a-sponsor',
'chapters',
'collective',
'contact',
'contribute',
'create',
'create-account',
'discover',
'donate',
'edit',
'expenses',
'faq',
'gift-card',
'gift-cards',
'gift-cards-next',
'gift-of-giving',
'help',
'home',
'host',
'hosts',
'how-it-works',
'join',
'join-free',
'learn-more',
'order',
'orders',
'pledge',
'pledges',
'privacypolicy',
'redeem',
'redeemed',
'register',
'search',
'signin',
'signup',
'subscriptions',
'tos',
'transactions',
'widgets',
];
/**
* Check if given `slug` could conflict with existing routes or
* if it's a reserved keyword.
*
* The list is mostly based on frontend `src/server/pages.js` file and
* `src/pages/static` content.
*
* @param {String} slug
*/
export function isBlacklistedCollectiveSlug(slug) {
return collectiveSlugBlacklist.includes(slug);
}
|
Update asset loading to be loaded in footer.
Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com> | <?php namespace Cello;
use \Asset,
\Event,
Orchestra\Acl,
Orchestra\Core as O;
class Core {
/**
* Start your engine.
*
* @static
* @access public
* @return void
*/
public static function start()
{
Acl::make('cello')->attach(O::memory());
// Append all Cello required assets for Orchestra Administrator
// Interface usage mainly on Resources page.
Event::listen('orchestra.started: backend', function()
{
$asset = Asset::container('orchestra.backend: footer');
$asset->script('redactor', 'bundles/orchestra/vendor/redactor/redactor.min.js', array('jquery', 'bootstrap'));
$asset->script('cello', 'bundles/cello/js/cello.min.js', array('redactor'));
$asset->style('redactor', 'bundles/orchestra/vendor/redactor/css/redactor.css', array('bootstrap'));
});
}
} | <?php namespace Cello;
use \Asset,
\Event,
Orchestra\Acl,
Orchestra\Core as O;
class Core {
/**
* Start your engine.
*
* @static
* @access public
* @return void
*/
public static function start()
{
Acl::make('cello')->attach(O::memory());
// Append all Cello required assets for Orchestra Administrator
// Interface usage mainly on Resources page.
Event::listen('orchestra.started: backend', function()
{
$asset = Asset::container('orchestra.backend');
$asset->script('redactor', 'bundles/orchestra/vendor/redactor/redactor.js', array('jquery', 'bootstrap'));
$asset->script('cello', 'bundles/cello/js/cello.min.js', array('redactor'));
$asset->style('redactor', 'bundles/orchestra/vendor/redactor/css/redactor.css', array('bootstrap'));
});
}
} |
Move main method to top of class | package net.zephyrizing.http_server;
public class HttpServer {
public static void main(String[] args) {
int portNumber;
if (args.length == 1) {
portNumber = Integer.parseInt(args[0]);
} else {
portNumber = 5000;
}
System.err.format("Starting server on port %d...", portNumber);
HttpServerSocket httpSocket = new HttpServerSocketImpl();
HttpServer server = new HttpServer(httpSocket, portNumber);
server.listen();
}
// Actual class begins
private HttpServerSocket serveSocket;
private int port;
public HttpServer(HttpServerSocket serveSocket, int port) {
this.serveSocket = serveSocket;
this.port = port;
}
public void listen() {
serveSocket.bind(port);
}
}
| package net.zephyrizing.http_server;
public class HttpServer {
private HttpServerSocket serveSocket;
private int port;
public HttpServer(HttpServerSocket serveSocket, int port) {
this.serveSocket = serveSocket;
this.port = port;
}
public void listen() {
serveSocket.bind(port);
}
public static void main(String[] args) {
int portNumber;
if (args.length == 1) {
portNumber = Integer.parseInt(args[0]);
} else {
portNumber = 5000;
}
System.err.format("Starting server on port %d...", portNumber);
HttpServerSocket httpSocket = new HttpServerSocketImpl();
HttpServer server = new HttpServer(httpSocket, portNumber);
server.listen();
}
}
|
Modify example to calculate leaf position | """
Steam and Leaf Plot
-------------------
This example shows how to make a steam and leaf plot.
"""
import altair as alt
import pandas as pd
import numpy as np
np.random.seed(42)
# Generating random data
original_data = pd.DataFrame({'samples':np.array(np.random.normal(50, 15, 100), dtype=np.int)})
# Splitting steam and leaf
original_data['stem'] = original_data['samples'].apply(lambda x: str(x)[:-1])
original_data['leaf'] = original_data['samples'].apply(lambda x: str(x)[-1])
original_data.sort_values(by=['stem', 'leaf'], inplace=True)
# Determining position
position = np.array([], dtype=np.int64)
for key, group in original_data.groupby('stem'):
position = np.hstack([position, [*group.reset_index().index.values]])
original_data['position'] = position + 1
# Creating stem and leaf plot
chart = alt.Chart(original_data).mark_text(align='left', baseline='middle', dx=-5).encode(
y = alt.Y('stem:N', axis=alt.Axis(title='', tickSize=0)),
x = alt.X('position:Q', axis=alt.Axis(title='', ticks=False,labels=False,grid=False)),
text = 'leaf:N'
).configure_axis(labelFontSize=20).configure_text(fontSize=20)
| """
Steam and Leaf Plot
-------------------
This example shows how to make a steam and leaf plot.
"""
import altair as alt
import pandas as pd
import numpy as np
np.random.seed(42)
# Generating Random Data
original_data = pd.DataFrame({'samples':np.array(np.random.normal(50, 15, 100), dtype=np.int)})
# Splitting Steam and Leaf
original_data['stem'] = original_data['samples'].apply(lambda x: str(x)[:-1])
original_data['leaf'] = original_data['samples'].apply(lambda x: str(x)[-1])
# Grouping Leafs for each Stem
grouped_data = pd.DataFrame(columns=['stem', 'leaf'])
for key, group in original_data.groupby('stem'):
grouped_data = grouped_data.append({'stem':key,
'leaf': ''.join(group['leaf'].sort_values())},
ignore_index=True)
# Plotting Stems and Leafs
chart = alt.Chart(grouped_data).mark_text(align='left', baseline='middle',dx=-40).encode(
y = alt.Y('stem', axis=alt.Axis(title='', tickSize=0)),
text = 'leaf'
).properties(width=400).configure_axis(labelFontSize=20).configure_text(fontSize=20) |
Test Jump Search: Test coverage improved to 94.12 | /* eslint-env mocha */
const jumpsearch = require('../../../src').algorithms.Searching.jumpsearch;
const assert = require('assert');
describe('Jump Search', () => {
it('should return -1 for empty array', () => {
const index = jumpsearch([], 1);
assert.equal(index, -1);
});
it('should return -1 for no element found in array', () => {
const index = jumpsearch([2, 3, 4, 5, 6], 1);
assert.equal(index, -1);
});
it('should return index of mid element', () => {
const index = jumpsearch([2, 3, 4, 5, 6], 4);
assert.equal(index, 2);
});
it('should return index of first element', () => {
const index = jumpsearch([2, 3, 4, 5, 6], 2);
assert.equal(index, 0);
});
it('should return index of last element', () => {
const index = jumpsearch([2, 3, 4, 5, 6], 6);
assert.equal(index, 4);
});
it('should return index of last element', () => {
const sortedArray = [];
for (let i = 0; i <= 100; i += 2) {
sortedArray.push(i);
}
assert.equal(jumpsearch(sortedArray, 6), 3);
assert.equal(jumpsearch(sortedArray, 103), -1);
assert.equal(jumpsearch(sortedArray, 79), -1);
});
});
| /* eslint-env mocha */
const jumpsearch = require('../../../src').algorithms.Searching.jumpsearch;
const assert = require('assert');
describe('Jump Search', () => {
it('should return -1 for empty array', () => {
const index = jumpsearch([], 1);
assert.equal(index, -1);
});
it('should return -1 for no element found in array', () => {
const index = jumpsearch([2, 3, 4, 5, 6], 1);
assert.equal(index, -1);
});
it('should return index of mid element', () => {
const index = jumpsearch([2, 3, 4, 5, 6], 4);
assert.equal(index, 2);
});
it('should return index of first element', () => {
const index = jumpsearch([2, 3, 4, 5, 6], 2);
assert.equal(index, 0);
});
it('should return index of last element', () => {
const index = jumpsearch([2, 3, 4, 5, 6], 6);
assert.equal(index, 4);
});
});
|
Add support for click and drag position adjustment | /**
* @file Holds all RoboPaint manual/auto painting mode specific code
*/
// Initialize the RoboPaint canvas Paper.js extensions & layer management.
rpRequire('paper_utils')(paper);
rpRequire('paper_hershey')(paper);
// Init defaults & settings
paper.settings.handleSize = 10;
// Animation frame callback
function onFrame(event) {
canvas.onFrame(event);
}
function onMouseDrag(event) {
// Use the mouse drag delta to change the X/Y position offset.
$('#hcenter').val(Math.round($('#hcenter').val()) + event.delta.x).change();
$('#vcenter').val(Math.round($('#vcenter').val()) + event.delta.y).change();
}
// Show preview paths
function onMouseMove(event) {
project.deselectAll();
if (event.item) {
event.item.selected = true;
}
}
function onMouseDown(event) {
if (event.item && event.item.parent === paper.actionLayer) {
paper.runPath(event.item);
}
// Delete specific items for debugging
if (event.item) {
if (event.item.children) {
paper.utils.ungroupAllGroups(event.item.parent);
} else {
event.item.remove();
}
}
}
canvas.paperInit(paper);
| /**
* @file Holds all RoboPaint manual/auto painting mode specific code
*/
// Initialize the RoboPaint canvas Paper.js extensions & layer management.
rpRequire('paper_utils')(paper);
rpRequire('paper_hershey')(paper);
// Init defaults & settings
paper.settings.handleSize = 10;
// Animation frame callback
function onFrame(event) {
canvas.onFrame(event);
}
// Show preview paths
function onMouseMove(event) {
project.deselectAll();
if (event.item) {
event.item.selected = true;
}
}
function onMouseDown(event) {
if (event.item && event.item.parent === paper.actionLayer) {
paper.runPath(event.item);
}
// Delete specific items for debugging
if (event.item) {
if (event.item.children) {
paper.utils.ungroupAllGroups(event.item.parent);
} else {
event.item.remove();
}
}
}
canvas.paperInit(paper);
|
Fix some component imports that were broken when refactoring them for component splitting | import { importComponent } from 'meteor/vulcan:lib';
importComponent("FieldErrors", () => require('../../components/vulcan-forms/FieldErrors'));
importComponent("FormErrors", () => require('../../components/vulcan-forms/FormErrors'));
importComponent("FormError", () => require('../../components/vulcan-forms/FormError'));
importComponent("FormComponent", () => require('../../components/vulcan-forms/FormComponent'));
importComponent(["FormNestedArrayLayout", "FormNestedArray", "IconRemove"] () => require('../../components/vulcan-forms/FormNestedArray'));
importComponent("FormNestedDivider", () => require('../../components/vulcan-forms/FormNestedDivider'));
importComponent("FormNestedFoot", () => require('../../components/vulcan-forms/FormNestedFoot'));
importComponent("FormNestedHead", () => require('../../components/vulcan-forms/FormNestedHead'));
importComponent(["FormNestedObjectLayout", "FormNestedObject"], () => require('../../components/vulcan-forms/FormNestedObject'));
importComponent(["FormNestedItemLayout", "FormNestedItem"], () => require('../../components/vulcan-forms/FormNestedItem'));
importComponent(["FormIntlItemLayout", "FormIntl"], () => require('../../components/vulcan-forms/FormIntl'));
importComponent(["FormGroupHeader", "FormGroupLayout", "FormGroup", "IconRight", "IconDown"], () => require('../../components/vulcan-forms/FormGroup'));
importComponent("SmartForm", () => require('../../components/vulcan-forms/FormWrapper'));
importComponent("Form", () => require('../../components/vulcan-forms/Form'));
| import { importComponent } from 'meteor/vulcan:lib';
importComponent("FieldErrors", () => require('../../components/vulcan-forms/FieldErrors'));
importComponent("FormErrors", () => require('../../components/vulcan-forms/FormErrors'));
importComponent("FormError", () => require('../../components/vulcan-forms/FormError'));
importComponent("FormComponent", () => require('../../components/vulcan-forms/FormComponent'));
importComponent("FormNestedArray", () => require('../../components/vulcan-forms/FormNestedArray'));
importComponent("FormNestedDivider", () => require('../../components/vulcan-forms/FormNestedDivider'));
importComponent("FormNestedFoot", () => require('../../components/vulcan-forms/FormNestedFoot'));
importComponent("FormNestedHead", () => require('../../components/vulcan-forms/FormNestedHead'));
importComponent("FormNestedObject", () => require('../../components/vulcan-forms/FormNestedObject'));
importComponent("FormNestedItem", () => require('../../components/vulcan-forms/FormNestedItem'));
importComponent("FormIntl", () => require('../../components/vulcan-forms/FormIntl'));
importComponent("FormGroup", () => require('../../components/vulcan-forms/FormGroup'));
importComponent("FormWrapper", () => require('../../components/vulcan-forms/FormWrapper'));
importComponent("Form", () => require('../../components/vulcan-forms/Form'));
|
Remove unused set*(Collection) methods on models | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Channel\Model;
use Doctrine\Common\Collections\Collection;
/**
* Interface implemented by objects related to multiple channels
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface ChannelsAwareInterface
{
/**
* @return Collection|ChannelInterface[]
*/
public function getChannels();
/**
* @param ChannelInterface $channel
*
* @return bool
*/
public function hasChannel(ChannelInterface $channel);
/**
* @param ChannelInterface $channel
*/
public function addChannel(ChannelInterface $channel);
/**
* @param ChannelInterface $channel
*/
public function removeChannel(ChannelInterface $channel);
}
| <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Component\Channel\Model;
use Doctrine\Common\Collections\Collection;
/**
* Interface implemented by objects related to multiple channels
*
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
interface ChannelsAwareInterface
{
/**
* @return Collection|ChannelInterface[]
*/
public function getChannels();
/**
* @param Collection $collection
*/
public function setChannels(Collection $collection);
/**
* @param ChannelInterface $channel
*
* @return bool
*/
public function hasChannel(ChannelInterface $channel);
/**
* @param ChannelInterface $channel
*/
public function addChannel(ChannelInterface $channel);
/**
* @param ChannelInterface $channel
*/
public function removeChannel(ChannelInterface $channel);
}
|
Remove unnecessary call to isoWeekday | import moment from "moment";
function initLocale(name, config) {
try {
moment.locale(name, config);
} catch (error) {
throw new Error(
"Locale prop is not in the correct format. \n Locale has to be in form of object, with keys of name and config. " +
error.message
);
}
}
function initMoment(date, locale) {
if (locale && locale.name) {
return moment(date).startOf("day").locale(locale.name);
} else {
return moment(date).startOf("day");
}
}
function getStartOfWeek(moment, isoStartDay = 1) {
let result = moment.clone().isoWeekday(isoStartDay);
if (moment.isoWeekday() < isoStartDay) {
return result.subtract(1, "week");
} else {
return result;
}
}
function getSelectedDayOfWeek(selectedDate, isoStartDay) {
let result = selectedDate.isoWeekday() - isoStartDay;
if (result < 0) {
result += 7;
}
return result;
}
export default { getSelectedDayOfWeek, getStartOfWeek, initLocale, initMoment };
| import moment from "moment";
function initLocale(name, config) {
try {
moment.locale(name, config);
} catch (error) {
throw new Error(
"Locale prop is not in the correct format. \n Locale has to be in form of object, with keys of name and config. " +
error.message
);
}
}
function initMoment(date, locale) {
if (locale && locale.name) {
return moment(date).startOf("day").locale(locale.name);
} else {
return moment(date).startOf("day");
}
}
function getStartOfWeek(moment, isoStartDay = 1) {
let result = moment.clone().isoWeekday(isoStartDay);
if (moment.isoWeekday() < isoStartDay) {
return result.subtract(1, "week");
} else {
return result.isoWeekday(isoStartDay);
}
}
function getSelectedDayOfWeek(selectedDate, isoStartDay) {
let result = selectedDate.isoWeekday() - isoStartDay;
if (result < 0) {
result += 7;
}
return result;
}
export default { getSelectedDayOfWeek, getStartOfWeek, initLocale, initMoment };
|
Update the USER command to take advantage of core capabilities as well | from twisted.words.protocols import irc
from txircd.modbase import Command
class UserCommand(Command):
def onUse(self, user, data):
if not user.username:
user.registered -= 1
user.username = data["ident"]
user.realname = data["gecos"]
if user.registered == 0:
user.register()
def processParams(self, user, params):
if user.registered == 0:
user.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)")
return {}
if params and len(params) < 4:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters")
return {}
ident = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12]
if not ident:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid")
return {}
return {
"user": user,
"ident": ident,
"gecos": params[3]
}
def Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn():
return {
"commands": {
"USER": UserCommand()
}
}
def cleanup():
del self.ircd.commands["USER"] | from twisted.words.protocols import irc
from txircd.modbase import Command
class UserCommand(Command):
def onUse(self, user, params):
if user.registered == 0:
self.sendMessage(irc.ERR_ALREADYREGISTRED, ":Unauthorized command (already registered)")
return
if params and len(params) < 4:
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Not enough parameters")
if not user.username:
user.registered -= 1
user.username = filter(lambda x: x in string.ascii_letters + string.digits + "-_", params[0])[:12]
if not user.username:
user.registered += 1
user.sendMessage(irc.ERR_NEEDMOREPARAMS, "USER", ":Your username is not valid")
return
user.realname = params[3]
if user.registered == 0:
user.register()
def Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn():
return {
"commands": {
"USER": UserCommand()
}
}
def cleanup():
del self.ircd.commands["USER"] |
Update default settings to development. | """
WSGI config for job_runner project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE", "job_runner.settings.env.development")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| """
WSGI config for job_runner project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "job_runner.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
Refactor out a bare except: statement
It now catches `Redirect.DoesNotExist`, returning the normal 404 page if
no redirect is found. Any other exception should not be caught here. | from django import http
from wagtail.wagtailredirects import models
# Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py
class RedirectMiddleware(object):
def process_response(self, request, response):
# No need to check for a redirect for non-404 responses.
if response.status_code != 404:
return response
# Get the path
path = models.Redirect.normalise_path(request.get_full_path())
# Find redirect
try:
redirect = models.Redirect.get_for_site(request.site).get(old_path=path)
except models.Redirect.DoesNotExist:
# No redirect found, return the 400 page
return response
if redirect.is_permanent:
return http.HttpResponsePermanentRedirect(redirect.link)
else:
return http.HttpResponseRedirect(redirect.link)
| from django import http
from wagtail.wagtailredirects import models
# Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py
class RedirectMiddleware(object):
def process_response(self, request, response):
# No need to check for a redirect for non-404 responses.
if response.status_code != 404:
return response
# Get the path
path = models.Redirect.normalise_path(request.get_full_path())
# Find redirect
try:
redirect = models.Redirect.get_for_site(request.site).get(old_path=path)
if redirect.is_permanent:
return http.HttpResponsePermanentRedirect(redirect.link)
else:
return http.HttpResponseRedirect(redirect.link)
except:
pass
return response
|
Use safe load for yaml. | """
This file contains the code needed for dealing with some of the mappings. Usually a map is just a
dictionary that needs to be loaded inside a variable.
This file carries the function to parse the files and the variables containing the dictionaries
themselves.
"""
import yaml
def load_mapping(filename):
"""
Load a map from a file. The format must be something that resembles the python dictionary.abs
We use the yaml library for that, as using eval() may be dangerous.
It will return the data loaded as a dictionary.
"""
with open(filename) as file:
content = yaml.safe_load(file.read())
return content
# Loaded data go here
tk_color_codes = load_mapping('maps/color_code_mapping.txt')
midi_notes = load_mapping('maps/midi_to_note_mapping.txt')
scale_notes = load_mapping('maps/note_to_midi_mapping.txt')
volume_positions = load_mapping('maps/volume_positions.txt')
volume_colors = load_mapping('maps/volume_colors.txt')
pad_notes = load_mapping('maps/pad_notes.txt')
layouts = load_mapping('maps/layouts.txt')
| """
This file contains the code needed for dealing with some of the mappings. Usually a map is just a
dictionary that needs to be loaded inside a variable.
This file carries the function to parse the files and the variables containing the dictionaries
themselves.
"""
import yaml
def load_mapping(filename):
"""
Load a map from a file. The format must be something that resembles the python dictionary.abs
We use the yaml library for that, as using eval() may be dangerous.
It will return the data loaded as a dictionary.
"""
with open(filename) as file:
content = yaml.load(file.read())
return content
# Loaded data go here
tk_color_codes = load_mapping('maps/color_code_mapping.txt')
midi_notes = load_mapping('maps/midi_to_note_mapping.txt')
scale_notes = load_mapping('maps/note_to_midi_mapping.txt')
volume_positions = load_mapping('maps/volume_positions.txt')
volume_colors = load_mapping('maps/volume_colors.txt')
pad_notes = load_mapping('maps/pad_notes.txt')
layouts = load_mapping('maps/layouts.txt')
|
Fix PHP notice from the wrong type hint | <?php
namespace WP_CLI;
use \Composer\DependencyResolver\Rule;
use \Composer\EventDispatcher\Event;
use \Composer\EventDispatcher\EventSubscriberInterface;
use \Composer\Installer\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 ) {
$operation_message = $event->getOperation()->__toString();
WP_CLI::log( ' - ' . $operation_message );
}
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( " - Warning: %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 ) {
$operation_message = $event->getOperation()->__toString();
WP_CLI::log( ' - ' . $operation_message );
}
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( " - Warning: %s", $composer_error ) );
}
}
}
}
|
Exit the program when the Node.js version is incompatible with The Lounge | #!/usr/bin/env node
"use strict";
process.chdir(__dirname);
// Perform node version check before loading any other files or modules
// Doing this check as soon as possible allows us to avoid ES6 parser errors or
// other issues
// Try to display messages nicely, but gracefully degrade if anything goes wrong
var pkg = require("./package.json");
if (!require("semver").satisfies(process.version, pkg.engines.node)) {
let colors;
let log;
try {
colors = require("colors/safe");
} catch (e) {
colors = {};
colors.green = colors.red = colors.bold = (x) => x;
}
try {
log = require("./src/log");
} catch (e) {
log = {};
log.error = (msg) => console.error(`[ERROR] ${msg}`); // eslint-disable-line no-console
}
log.error(`The Lounge requires Node.js ${colors.green(pkg.engines.node)} (current version: ${colors.red(process.version)})`);
log.error(colors.bold("Please upgrade Node.js in order to use The Lounge"));
log.error("See https://nodejs.org/en/download/package-manager/ for more details");
process.exit(1);
}
require("./src/command-line");
| #!/usr/bin/env node
"use strict";
process.chdir(__dirname);
// Perform node version check before loading any other files or modules
// Doing this check as soon as possible allows us to avoid ES6 parser errors or
// other issues
// Try to display warnings nicely, but gracefully degrade if anything goes wrong
var pkg = require("./package.json");
if (!require("semver").satisfies(process.version, pkg.engines.node)) {
let colors;
let log;
try {
colors = require("colors/safe");
} catch (e) {
colors = {};
colors.green = colors.red = colors.bold = (x) => x;
}
try {
log = require("./src/log");
} catch (e) {
log = {};
log.warn = (msg) => console.error(`[WARN] ${msg}`); // eslint-disable-line no-console
}
log.warn(`The Lounge requires Node.js ${colors.green(pkg.engines.node)} (current version: ${colors.red(process.version)})`);
log.warn(colors.bold("We strongly encourage you to upgrade Node.js"));
log.warn("See https://nodejs.org/en/download/package-manager/ for more details");
}
require("./src/command-line");
|
Check for articles to convert to speech and upload to amazon every 15 minutes. | <?php namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
'App\Console\Commands\ConvertToSpeech',
'App\Console\Commands\PocketSynchronise',
'App\Console\Commands\UploadLocalFile',
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('pocket:synchronise')->hourly();
$schedule->command('articles:convert')->cron('*/15 * * * * *');
$schedule->command('articles:upload')->cron('*/15 * * * * *');
}
}
| <?php namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel {
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
'App\Console\Commands\ConvertToSpeech',
'App\Console\Commands\PocketSynchronise',
'App\Console\Commands\UploadLocalFile',
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('pocket:synchronise')->hourly();
$schedule->command('articles:convert')->cron('15 * * * * *');
$schedule->command('articles:upload')->cron('30 * * * * *');
}
}
|
Remove actions from each lemma | "use strict";
import h from "yasmf-h";
import el from "$LIB/templates/el";
import L from "$APP/localization/localization";
import glyph from "$WIDGETS/glyph";
import list from "$WIDGETS/list";
import listItem from "$WIDGETS/listItem";
import listItemContents from "$WIDGETS/listItemContents";
import listItemActions from "$WIDGETS/listItemActions";
import lemmaActions from "./lemmaActions";
export default function lemmaList(lemmas) {
return list({
contents: lemmas.map( lemma => {
return listItem({
contents: listItemContents({
props: {
value: lemma
},
contents: [
h.el("div.y-flex", lemma)
]
})
});
})
});
}
| "use strict";
import h from "yasmf-h";
import el from "$LIB/templates/el";
import L from "$APP/localization/localization";
import glyph from "$WIDGETS/glyph";
import list from "$WIDGETS/list";
import listItem from "$WIDGETS/listItem";
import listItemContents from "$WIDGETS/listItemContents";
import listItemActions from "$WIDGETS/listItemActions";
import lemmaActions from "./lemmaActions";
export default function lemmaList(lemmas) {
return list({
contents: lemmas.map( lemma => {
return listItem({
contents: listItemContents({
props: {
value: lemma
},
contents: [
h.el("div.y-flex", lemma)
]
}),
actions: listItemActions({ contents: lemmaActions() })
});
})
});
}
|
Use wildcard to also accept e.g. list of `RootElement`s | package de.retest.recheck.ui.descriptors;
import java.util.ArrayList;
import java.util.List;
public class ElementUtil {
private ElementUtil() {}
public static List<Element> flattenAllElements( final List<? extends Element> elements ) {
final List<Element> flattened = new ArrayList<>();
for ( final Element element : elements ) {
flattened.add( element );
flattened.addAll( flattenChildElements( element ) );
}
return flattened;
}
public static List<Element> flattenChildElements( final Element element ) {
final List<Element> flattened = new ArrayList<>();
for ( final Element childElement : element.getContainedElements() ) {
flattened.add( childElement );
flattened.addAll( flattenChildElements( childElement ) );
}
return flattened;
}
public static boolean pathEquals( final Element element0, final Element element1 ) {
return element0.getIdentifyingAttributes().getPathTyped()
.equals( element1.getIdentifyingAttributes().getPathTyped() );
}
}
| package de.retest.recheck.ui.descriptors;
import java.util.ArrayList;
import java.util.List;
public class ElementUtil {
private ElementUtil() {}
public static List<Element> flattenAllElements( final List<Element> elements ) {
final List<Element> flattened = new ArrayList<>();
for ( final Element element : elements ) {
flattened.add( element );
flattened.addAll( flattenChildElements( element ) );
}
return flattened;
}
public static List<Element> flattenChildElements( final Element element ) {
final List<Element> flattened = new ArrayList<>();
for ( final Element childElement : element.getContainedElements() ) {
flattened.add( childElement );
flattened.addAll( flattenChildElements( childElement ) );
}
return flattened;
}
public static boolean pathEquals( final Element element0, final Element element1 ) {
return element0.getIdentifyingAttributes().getPathTyped()
.equals( element1.getIdentifyingAttributes().getPathTyped() );
}
}
|
[FEATURE] Add new task for generating vhosts | <?php
namespace Deployer;
set('vhost_template', '<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot "{{deploy_path}}/current"
<Directory "{{deploy_path}}/current">
Options -Indexes
Options FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
{{vhost_server_names}}
</VirtualHost>
');
set('vhost_ssl_template', '<VirtualHost *:443>
ServerAdmin webmaster@localhost
DocumentRoot "{{deploy_path}}/current"
<Directory "{{deploy_path}}/current">
Options -Indexes
Options FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
{{vhost_server_names}}
SSLEngine on
SSLCertificateFile "{{vhost_ssl_path}}/domain.pem"
SSLCertificateKeyFile "{{vhost_ssl_path}}/domain.key"
SSLCACertificateFile "{{vhost_ssl_path}}/domain.intermediate"
</VirtualHost>');
set('vhost_path', getenv('VHOSTS_PATH'));
set('vhost_ssl_path', getenv('VHOSTS_SSLCERT_PATH'));
| <?php
namespace Deployer;
set('vhost_template', '<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot "{{deploy_path}}/current"
<Directory "{{deploy_path}}/current">
Options -Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
{{vhost_server_names}}
</VirtualHost>
');
set('vhost_ssl_template', '<VirtualHost *:443>
ServerAdmin webmaster@localhost
DocumentRoot "{{deploy_path}}/current"
<Directory "{{deploy_path}}/current">
Options -Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
{{vhost_server_names}}
SSLEngine on
SSLCertificateFile "~/.ssh/ssl/domain.pem"
SSLCertificateKeyFile "~/.ssh/ssl/domain.key"
SSLCACertificateFile "~/.ssh/ssl/domain.intermediate"
</VirtualHost>');
set('vhost_path', getenv('VHOSTS_PATH'));
|
Add call static helper method to service context | <?php
/**
*
*/
namespace Mvc5\Service;
use Mvc5\Exception;
final class Context
{
/**
* @var Service
*/
protected static $service;
/**
* @param Service|null $service
*/
function __construct(Service $service = null)
{
$service && $this->bind($service);
}
/**
* @param Service $service
* @return callable|Manager|Service
*/
static function bind(Service $service)
{
isset(static::$service) &&
Exception::runtime('Service already exists');
return static::$service = $service;
}
/**
* @return callable|Manager|Service
*/
static function service()
{
return static::$service ?: Exception::runtime('Service does not exist');
}
/**
* @param $name
* @param array $args
* @return mixed
*/
static function __callStatic($name, array $args)
{
return static::service()->call($name, $args);
}
/**
* @param Service $service
*/
function __invoke(Service $service)
{
$this->bind($service);
}
}
| <?php
/**
*
*/
namespace Mvc5\Service;
use Mvc5\Exception;
final class Context
{
/**
* @var Service
*/
protected static $service;
/**
* @param Service|null $service
*/
function __construct(Service $service = null)
{
$service && $this->bind($service);
}
/**
* @param Service $service
* @return callable|Manager|Service
*/
static function bind(Service $service)
{
isset(static::$service) &&
Exception::runtime('Service already exists');
return static::$service = $service;
}
/**
* @return callable|Manager|Service
*/
static function service()
{
return static::$service ?: Exception::runtime('Service does not exist');
}
/**
* @param Service $service
*/
function __invoke(Service $service)
{
$this->bind($service);
}
}
|
lxd/shutdown: Fix typo in error handling
Signed-off-by: Stéphane Graber <089afc6d81f66f1168a9849e15660feae286e024@ubuntu.com> | package main
import (
"fmt"
"strings"
"time"
"github.com/lxc/lxd/client"
)
func cmdShutdown(args *Args) error {
connArgs := &lxd.ConnectionArgs{
SkipGetServer: true,
}
c, err := lxd.ConnectLXDUnix("", connArgs)
if err != nil {
return err
}
_, _, err = c.RawQuery("PUT", "/internal/shutdown", nil, "")
if err != nil && !strings.HasSuffix(err.Error(), ": EOF") {
// NOTE: if we got an EOF error here it means that the daemon
// has shutdown so quickly that it already closed the unix
// socket. We consider the daemon dead in this case.
return err
}
chMonitor := make(chan bool, 1)
go func() {
monitor, err := c.GetEvents()
if err != nil {
close(chMonitor)
return
}
monitor.Wait()
close(chMonitor)
}()
if args.Timeout > 0 {
select {
case <-chMonitor:
break
case <-time.After(time.Second * time.Duration(args.Timeout)):
return fmt.Errorf("LXD still running after %ds timeout.", args.Timeout)
}
} else {
<-chMonitor
}
return nil
}
| package main
import (
"fmt"
"strings"
"time"
"github.com/lxc/lxd/client"
)
func cmdShutdown(args *Args) error {
connArgs := &lxd.ConnectionArgs{
SkipGetServer: true,
}
c, err := lxd.ConnectLXDUnix("", connArgs)
if err != nil {
return err
}
_, _, err = c.RawQuery("PUT", "/internal/shutdown", nil, "")
if err != nil && strings.HasSuffix(err.Error(), ": EOF") {
// NOTE: if we got an EOF error here it means that the daemon
// has shutdown so quickly that it already closed the unix
// socket. We consider the daemon dead in this case.
return err
}
chMonitor := make(chan bool, 1)
go func() {
monitor, err := c.GetEvents()
if err != nil {
close(chMonitor)
return
}
monitor.Wait()
close(chMonitor)
}()
if args.Timeout > 0 {
select {
case <-chMonitor:
break
case <-time.After(time.Second * time.Duration(args.Timeout)):
return fmt.Errorf("LXD still running after %ds timeout.", args.Timeout)
}
} else {
<-chMonitor
}
return nil
}
|
Add slug field to Dataset model. Using slugs for API looks better than pk. | from django.db import models
from django.contrib.auth.models import User
class DatasetLicence(models.Model):
title = models.CharField(max_length=255)
short_title = models.CharField(max_length=30)
url = models.URLField()
summary = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class FileFormat(models.Model):
extension = models.CharField(max_length=10)
description = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def get_dataset_upload_path(self, instance, filename):
return '/%s/' % instance.author.username
class Dataset(models.Model):
title = models.CharField(max_length=255)
licence = models.ForeignKey('DatasetLicence')
file = models.FileField(upload_to=get_dataset_upload_path)
file_format = models.ForeignKey('FileFormat')
description = models.TextField()
author = models.ForeignKey(User)
slug = models.SlugField(max_length=40)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
| from django.db import models
from django.contrib.auth.models import User
class DatasetLicence(models.Model):
title = models.CharField(max_length=255)
short_title = models.CharField(max_length=30)
url = models.URLField()
summary = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class FileFormat(models.Model):
extension = models.CharField(max_length=10)
description = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def get_dataset_upload_path(self, instance, filename):
return '/%s/' % instance.author.username
class Dataset(models.Model):
title = models.CharField(max_length=255)
licence = models.ForeignKey('DatasetLicence')
file = models.FileField(upload_to=get_dataset_upload_path)
file_format = models.ForeignKey('FileFormat')
description = models.TextField()
author = models.ForeignKey(User)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
|
Add reconnect/disconnect events to fallback connection. | function build_url(host, command, node = "") {
if( node == "local" ){
return 'http://' + host + '/api/' + encodeURI(command).replace(/#/g, '%23');
} else {
return 'http://' + host + '/api/' + encodeURI(node) + "/" + encodeURI(command).replace(/#/g, '%23');
}
}
class WobserverApiFallback {
constructor(host, node = "local") {
this.host = host;
this.node = node;
this.connected = true;
}
command(command, data = null) {
fetch(build_url(this.host, command, this.node))
}
command_promise(command, data = null) {
return fetch(build_url(this.host, command, this.node))
.then(res => res.json())
.then(data => { return {
data: data,
timestamp: Date.now() / 1000 | 0,
type: command,
} } )
.then(e => {
if( !this.connected ){
this.connected = true;
this.on_reconnect()
}
return e;
})
.catch(_ => {
this.connected = false;
this.on_disconnect();
});
}
set_node(node) {
this.node = node;
}
}
export{ WobserverApiFallback }
| function build_url(host, command, node = "") {
if( node == "local" ){
return 'http://' + host + '/api/' + encodeURI(command).replace(/#/g, '%23');
} else {
return 'http://' + host + '/api/' + encodeURI(node) + "/" + encodeURI(command).replace(/#/g, '%23');
}
}
class WobserverApiFallback {
constructor(host, node = "local") {
this.host = host;
this.node = node;
}
command(command, data = null) {
console.log('Send fallback command');
}
command_promise(command, data = null) {
return fetch(build_url(this.host, command, this.node))
.then(res => res.json())
.then(data => { return {
data: data,
timestamp: Date.now() / 1000 | 0,
type: command,
} } )
.catch( _ => {} );
}
set_node(node) {
this.node = node;
}
}
export{ WobserverApiFallback }
|
Prepare to supply fixtures from DOM elements | package pl.minidmnv.apple.source.fixture.repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import pl.minidmnv.apple.source.fixture.data.Fixture;
import pl.minidmnv.apple.source.fixture.repository.picker.FSFixtureDOMElementPicker;
import pl.minidmnv.apple.source.fixture.tray.FixtureTray;
/**
* @author mnicinski.
*/
public class FlashScoreFixtureRepository implements FixtureRepository {
private FixtureTray fixtureTray;
private FSFixtureDOMElementPicker picker = new FSFixtureDOMElementPicker();
@Override
public List<Fixture> getUpcomingFixtures(Integer limit) {
List fixtures = new ArrayList();
Optional<Document> upcomingFixturesDocument = fixtureTray.getUpcomingFixturesDocument();
if (upcomingFixturesDocument.isPresent()) {
Document doc = upcomingFixturesDocument.get();
fixtures = parseFixtures(doc);
}
return fixtures;
}
private List parseFixtures(Document doc) {
picker.init(doc);
Elements elements = picker.pickUpcomingFixtures();
return elements.stream()
.map(this::transformStageScheduledElementToFixture)
.collect(Collectors.toList());
}
private Fixture transformStageScheduledElementToFixture(Element e) {
Fixture result = new Fixture();
return result;
}
}
| package pl.minidmnv.apple.source.fixture.repository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import pl.minidmnv.apple.source.fixture.data.Fixture;
import pl.minidmnv.apple.source.fixture.repository.picker.FSFixtureDOMElementPicker;
import pl.minidmnv.apple.source.fixture.tray.FixtureTray;
/**
* @author mnicinski.
*/
public class FlashScoreFixtureRepository implements FixtureRepository {
private FixtureTray fixtureTray;
private FSFixtureDOMElementPicker picker = new FSFixtureDOMElementPicker();
@Override
public List<Fixture> getUpcomingFixtures(Integer limit) {
List fixtures = new ArrayList();
Optional<Document> upcomingFixturesDocument = fixtureTray.getUpcomingFixturesDocument();
if (upcomingFixturesDocument.isPresent()) {
Document doc = upcomingFixturesDocument.get();
picker.init(doc);
fixtures = parseFixtures(doc);
}
return fixtures;
}
private List parseFixtures(Document document) {
Elements elements = picker.pickUpcomingFixtures();
return null;
}
}
|
Set echo to false; testing to true | 'use strict';
/*
* Copyright 2014 Next Century Corporation
* 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.
*
*/
var XDATA = {};
XDATA.ACTIVITY_LOGGER_URL = "http://xd-draper.xdata.data-tactics-corp.com:1337";
XDATA.COMPONENT = "Neon Demo";
XDATA.COMPONENT_VERSION = "0.8.0-SNAPSHOT";
XDATA.activityLogger = new activityLogger('lib/draperlab/draper.activity_worker-2.1.1.js').echo(false).testing(true);
// Register the xdata logger with a server.
XDATA.activityLogger.registerActivityLogger(XDATA.ACTIVITY_LOGGER_URL,
XDATA.COMPONENT,
XDATA.COMPONENT_VERSION); | 'use strict';
/*
* Copyright 2014 Next Century Corporation
* 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.
*
*/
var XDATA = {};
XDATA.ACTIVITY_LOGGER_URL = "http://xd-draper.xdata.data-tactics-corp.com:1337";
XDATA.COMPONENT = "Neon Demo";
XDATA.COMPONENT_VERSION = "0.8.0-SNAPSHOT";
XDATA.activityLogger = new activityLogger('lib/draperlab/draper.activity_worker-2.1.1.js').echo(true).testing(false);
// Register the xdata logger with a server.
XDATA.activityLogger.registerActivityLogger(XDATA.ACTIVITY_LOGGER_URL,
XDATA.COMPONENT,
XDATA.COMPONENT_VERSION); |
Change the colours of the 'A' and 'G' to make them slightly darker and them more consistent with the colours of the genotypes on the website | // $Revision$
Ensembl.Panel.PopulationGraph = Ensembl.Panel.Piechart.extend({
init: function () {
// Allele colours
this.graphColours = {
'A' : '#00A000',
'T' : '#FF0000',
'G' : '#FFCC00',
'C' : '#0000FF',
'-' : '#000000',
'default' : [ '#008080', '#FF00FF', '#7B68EE' ] // Other colours if the allele is not A, T, G, C or -
};
this.base();
},
toggleContent: function (el) {
if (el.hasClass('open') && !el.data('done')) {
this.base(el);
this.makeGraphs($('.pie_chart > div', '.' + el.attr('rel')).map(function () { return this.id.replace('graphHolder', ''); }).toArray());
el.data('done', true);
} else {
this.base(el);
}
el = null;
}
});
| // $Revision$
Ensembl.Panel.PopulationGraph = Ensembl.Panel.Piechart.extend({
init: function () {
// Allele colours
this.graphColours = {
'A' : '#00BB00',
'T' : '#FF0000',
'G' : '#FFD700',
'C' : '#0000FF',
'default' : [ '#222222', '#FF00FF', '#008080', '#7B68EE' ] // Other colours if the allele is not A, T, G or C
};
this.base();
},
toggleContent: function (el) {
if (el.hasClass('open') && !el.data('done')) {
this.base(el);
this.makeGraphs($('.pie_chart > div', '.' + el.attr('rel')).map(function () { return this.id.replace('graphHolder', ''); }).toArray());
el.data('done', true);
} else {
this.base(el);
}
el = null;
}
});
|
Add some debug when playing | #!/usr/bin/env python
import os
import sys
import requests
import re
from bot import RandomBot
SERVER_HOST = 'http://localhost:9000'
trainingState = requests.post(SERVER_HOST + '/api/training/alone').json()
state = trainingState
bot = RandomBot()
def move(url, direction):
r = requests.post(url, {'dir': direction})
return r.json()
def start(server_url):
def play(state):
if (state['game']['finished']):
print('game finished')
else:
url = state['playUrl']
direction = bot.move(state)
newState = move(state['playUrl'], direction)
print("Playing turn %d with direction %s" % (state['game']['turn'], direction))
play(newState)
print("Start: " + state['viewUrl'])
play(state)
if __name__ == "__main__":
if (len(sys.argv) > 1):
SERVER_HOST = sys.argv[1]
start(sys.argv[1])
else:
print('Specify the server, ex: "http://localhost:9000"')
| #!/usr/bin/env python
import os
import sys
import requests
import re
from bot import RandomBot
SERVER_HOST = 'http://localhost:9000'
trainingState = requests.post(SERVER_HOST + '/api/training/alone').json()
state = trainingState
bot = RandomBot()
def move(url, direction):
r = requests.post(url, {'dir': direction})
return r.json()
def start(server_url):
def play(state):
if (state['game']['finished']):
print('game finished')
else:
url = state['playUrl']
direction = bot.move(state)
newState = move(state['playUrl'], direction)
play(newState)
print("Start: " + state['viewUrl'])
play(state)
if __name__ == "__main__":
if (len(sys.argv) > 1):
SERVER_HOST = sys.argv[1]
start(sys.argv[1])
else:
print('Specify the server, ex: "http://localhost:9000"')
|
Add lang to global export list. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011-2014, Nigel Small
#
# 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.
__author__ = "Nigel Small <nigel@nigelsmall.com>"
__copyright__ = "2011-2014, Nigel Small"
__email__ = "nigel@nigelsmall.com"
__license__ = "Apache License, Version 2.0"
__package__ = "py2neo"
__version__ = "2.0.beta" # TODO: update this before release
from py2neo.batch import *
from py2neo.core import *
from py2neo.cypher import *
from py2neo.error import *
from py2neo.lang import *
from py2neo.legacy import *
from py2neo.packages.httpstream.watch import watch
node = Node.cast
rel = Relationship.cast
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011-2014, Nigel Small
#
# 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.
__author__ = "Nigel Small <nigel@nigelsmall.com>"
__copyright__ = "2011-2014, Nigel Small"
__email__ = "nigel@nigelsmall.com"
__license__ = "Apache License, Version 2.0"
__package__ = "py2neo"
__version__ = "2.0.beta" # TODO: update this before release
from py2neo.batch import *
from py2neo.core import *
from py2neo.cypher import *
from py2neo.error import *
from py2neo.legacy import *
from py2neo.packages.httpstream.watch import watch
node = Node.cast
rel = Relationship.cast
|
Fix for cluster creation dialog | casper.start().loadPage('#clusters');
casper.then(function() {
this.test.comment('Testing cluster list page');
this.test.assertExists('.cluster-list', 'Cluster container exists');
this.test.assertExists('.create-cluster', 'Cluster creation control exists');
});
casper.then(function() {
this.test.comment('Testing cluster creation');
var name = 'Test Cluster';
this.click('.create-cluster');
this.test.assertSelectorAppears('.modal', 'Cluster creation dialog opens');
this.test.assertSelectorAppears('.modal form select[name=release] option', 'Release select box updates with releases');
this.then(function() {
this.fill('form.create-cluster-form', {name: name});
this.fill('form.rhel-license', {username: 'username', password: 'password'});
this.click('.create-cluster-btn');
});
this.test.assertSelectorDisappears('.modal', 'Cluster creation dialog closes after from submission');
this.test.assertSelectorAppears('.cluster-list a.clusterbox', 'Created cluster appears in list');
this.then(function() {
this.test.assertSelectorHasText('.cluster-list a.clusterbox .cluster-name', name, 'Created cluster has specified name');
})
});
casper.run(function() {
this.test.done();
});
| casper.start().loadPage('#clusters');
casper.then(function() {
this.test.comment('Testing cluster list page');
this.test.assertExists('.cluster-list', 'Cluster container exists');
this.test.assertExists('.create-cluster', 'Cluster creation control exists');
});
casper.then(function() {
this.test.comment('Testing cluster creation');
var name = 'Test Cluster';
this.click('.create-cluster');
this.test.assertSelectorAppears('.modal', 'Cluster creation dialog opens');
this.test.assertSelectorAppears('.modal form select[name=release] option', 'Release select box updates with releases');
this.then(function() {
this.fill('.modal form', {name: name});
this.click('.create-cluster-btn');
});
this.test.assertSelectorDisappears('.modal', 'Cluster creation dialog closes after from submission');
this.test.assertSelectorAppears('.cluster-list a.clusterbox', 'Created cluster appears in list');
this.then(function() {
this.test.assertSelectorHasText('.cluster-list a.clusterbox .cluster-name', name, 'Created cluster has specified name');
})
});
casper.run(function() {
this.test.done();
});
|
Fix settings; tests now passing | from . import model
from . import routes
from . import views
MODELS = [model.DropboxUserSettings]
USER_SETTINGS_MODEL = model.DropboxUserSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
| from . import model
from . import routes
from . import views
MODELS = [model.AddonDropboxUserSettings] # TODO Other models needed? , model.AddonDropboxNodeSettings, model.DropboxGuidFile]
USER_SETTINGS_MODEL = model.AddonDropboxNodeSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
|
Add class for competitor info |
// Copyright 2021 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.
package com.google.sps.data;
import com.google.auto.value.AutoValue;
/**
* Class representing user data specific to a competition
*/
@AutoValue
public abstract class CompetitorInfo {
public static CompetitorInfo create(String name, String email, int rank, int rankYesterday, long netWorth,
long amountAvailable, int numInvestments) {
return new AutoValue_CompetitorInfo(name, email, rank, rankYesterday, netWorth, amountAvailable, numInvestments);
}
/** The competitor's name */
public abstract String name();
/** The competitor's Google email */
public abstract String email();
/** Competitor's rank */
public abstract int rank();
/** Competitor's rank yesterday */
public abstract int rankYesterday();
/** The networth of the competitor */
public abstract long netWorth();
/** The amount the user has available for additional investments */
public abstract long amountAvailable();
/** The number of investments owned by this competitor */
public abstract int numInvestments();
} |
// Copyright 2021 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.
package com.google.sps.data;
import com.google.auto.value.AutoValue;
/**
* Class representing user data specific to a competition
*/
@AutoValue
public abstract class CompetitorInfo {
public static CompetitorInfo create(long id, String name, String email, long netWorth, long amountAvailable) {
return new AutoValue_CompetitorInfo(id, name, email, netWorth, amountAvailable);
}
/** The id of the competitor */
public abstract long id();
/** The competitor's name */
public abstract String name();
/** The competitor's Google email */
public abstract String email();
/** The networth of the competitor */
public abstract long netWorth();
/** The amount the user has available for additional investments */
public abstract long amountAvailable();
} |
Rename extension option to format in view factory | <?php
namespace Perfumer\MVC\View;
use Perfumer\MVC\Bundler\Bundler;
class ViewFactory
{
protected $templating;
/**
* @var Bundler
*/
protected $bundler;
protected $options = [];
public function __construct($templating, Bundler $bundler, $options = [])
{
$this->templating = $templating;
$this->bundler = $bundler;
$default_options = [
'format' => 'php'
];
$this->options = array_merge($default_options, $options);
}
public function getInstance()
{
return new View($this);
}
/**
* @return Bundler
*/
public function getBundler()
{
return $this->bundler;
}
public function getTemplating()
{
return $this->templating;
}
public function getOption($name)
{
return isset($this->options[$name]) ? $this->options[$name] : null;
}
} | <?php
namespace Perfumer\MVC\View;
use Perfumer\MVC\Bundler\Bundler;
class ViewFactory
{
protected $templating;
/**
* @var Bundler
*/
protected $bundler;
protected $options = [];
public function __construct($templating, Bundler $bundler, $options = [])
{
$this->templating = $templating;
$this->bundler = $bundler;
$default_options = [
'extension' => 'php'
];
$this->options = array_merge($default_options, $options);
}
public function getInstance()
{
return new View($this);
}
/**
* @return Bundler
*/
public function getBundler()
{
return $this->bundler;
}
public function getTemplating()
{
return $this->templating;
}
public function getOption($name)
{
return isset($this->options[$name]) ? $this->options[$name] : null;
}
} |
Check if Xdebug is loaded | <?php
if (!extension_loaded('xdebug')) {
die('The Xdebug extension is not loaded. No code coverage will be generated.');
}
if (!file_exists($strInputFile = $argv[1])) {
throw new InvalidArgumentException('Invalid input file provided');
}
if (!($fltPercentage = min(100,max(0,(int)$argv[2])))) {
throw new InvalidArgumentException('An integer checked percentage must be given as second parameter');
}
$objXml = new SimpleXMLElement(file_get_contents($strInputFile));
$intTotalElements = 0;
$intCheckedElements = 0;
foreach ($objXml->xpath('//metrics') as $objMetricXml) {
$intTotalElements += (int)$objMetricXml['elements'];
$intCheckedElements += (int)$objMetricXml['coveredelements'];
}
if (($fltCoverage = ($intCheckedElements/$intTotalElements)*100) < $fltPercentage) {
echo "Code coverage is {$fltCoverage}%, which is below the accepted {$fltPercentage}%".PHP_EOL;
exit(1);
}
echo "Code coverage is {$fltCoverage}% - OK!".PHP_EOL;
| <?php
if (!file_exists($strInputFile = $argv[1])) {
throw new InvalidArgumentException('Invalid input file provided');
}
if (!($fltPercentage = min(100,max(0,(int)$argv[2])))) {
throw new InvalidArgumentException('An integer checked percentage must be given as second parameter');
}
$objXml = new SimpleXMLElement(file_get_contents($strInputFile));
$intTotalElements = 0;
$intCheckedElements = 0;
foreach ($objXml->xpath('//metrics') as $objMetricXml) {
$intTotalElements += (int)$objMetricXml['elements'];
$intCheckedElements += (int)$objMetricXml['coveredelements'];
}
if (($fltCoverage = ($intCheckedElements/$intTotalElements)*100) < $fltPercentage) {
echo "Code coverage is {$fltCoverage}%, which is below the accepted {$fltPercentage}%".PHP_EOL;
exit(1);
}
echo "Code coverage is {$fltCoverage}% - OK!".PHP_EOL;
|
Convert dockerd to use cobra and pflag
Signed-off-by: Daniel Nephin <6347c07ae509164cffebfb1e2a0d6ed64958db19@docker.com> | package opts
import (
"fmt"
"net"
)
// IPOpt holds an IP. It is used to store values from CLI flags.
type IPOpt struct {
*net.IP
}
// NewIPOpt creates a new IPOpt from a reference net.IP and a
// string representation of an IP. If the string is not a valid
// IP it will fallback to the specified reference.
func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt {
o := &IPOpt{
IP: ref,
}
o.Set(defaultVal)
return o
}
// Set sets an IPv4 or IPv6 address from a given string. If the given
// string is not parseable as an IP address it returns an error.
func (o *IPOpt) Set(val string) error {
ip := net.ParseIP(val)
if ip == nil {
return fmt.Errorf("%s is not an ip address", val)
}
*o.IP = ip
return nil
}
// String returns the IP address stored in the IPOpt. If stored IP is a
// nil pointer, it returns an empty string.
func (o *IPOpt) String() string {
if *o.IP == nil {
return ""
}
return o.IP.String()
}
// Type returns the type of the option
func (o *IPOpt) Type() string {
return "ip"
}
| package opts
import (
"fmt"
"net"
)
// IPOpt holds an IP. It is used to store values from CLI flags.
type IPOpt struct {
*net.IP
}
// NewIPOpt creates a new IPOpt from a reference net.IP and a
// string representation of an IP. If the string is not a valid
// IP it will fallback to the specified reference.
func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt {
o := &IPOpt{
IP: ref,
}
o.Set(defaultVal)
return o
}
// Set sets an IPv4 or IPv6 address from a given string. If the given
// string is not parseable as an IP address it returns an error.
func (o *IPOpt) Set(val string) error {
ip := net.ParseIP(val)
if ip == nil {
return fmt.Errorf("%s is not an ip address", val)
}
*o.IP = ip
return nil
}
// String returns the IP address stored in the IPOpt. If stored IP is a
// nil pointer, it returns an empty string.
func (o *IPOpt) String() string {
if *o.IP == nil {
return ""
}
return o.IP.String()
}
|
Fix request_parser services priority compiler pass | <?php
/*
* This file is part of the PostmanGeneratorBundle package.
*
* (c) Vincent Chalamon <vincentchalamon@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PostmanGeneratorBundle\DependencyInjection\CompilerPass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class RequestParserCompilerPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$registryDefinition = $container->getDefinition('postman.request_parser.chain');
$requestParsers = [];
foreach ($container->findTaggedServiceIds('postman.request_parser') as $serviceId => $tags) {
$attributes = $container->getDefinition($serviceId)->getTag('postman.request_parser');
$priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;
$requestParsers[$priority][] = new Reference($serviceId);
}
krsort($requestParsers);
$registryDefinition->replaceArgument(0, call_user_func_array('array_merge', $requestParsers));
}
}
| <?php
/*
* This file is part of the PostmanGeneratorBundle package.
*
* (c) Vincent Chalamon <vincentchalamon@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PostmanGeneratorBundle\DependencyInjection\CompilerPass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class RequestParserCompilerPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$registryDefinition = $container->getDefinition('postman.request_parser.chain');
$requestParsers = [];
foreach ($container->findTaggedServiceIds('postman.request_parser') as $serviceId => $tags) {
$attributes = $container->getDefinition($serviceId)->getTag('postman.request_parser');
$priority = isset($attributes['priority']) ? $attributes['priority'] : 0;
$requestParsers[$priority][] = new Reference($serviceId);
}
krsort($requestParsers);
$registryDefinition->replaceArgument(0, call_user_func_array('array_merge', $requestParsers));
}
}
|
Disable timestamps on city model | <?php namespace Octommerce\Octommerce\Models;
use Model;
/**
* City Model
*/
class City extends Model
{
/**
* @var string The database table used by the model.
*/
public $table = 'octommerce_octommerce_cities';
public $timestamps = false;
/**
* @var array Guarded fields
*/
protected $guarded = ['*'];
/**
* @var array Fillable fields
*/
protected $fillable = [];
/**
* @var array Relations
*/
public $hasOne = [];
public $hasMany = [];
public $belongsTo = [
'state' => 'RainLab\Location\Models\State',
];
public $belongsToMany = [];
public $morphTo = [];
public $morphOne = [];
public $morphMany = [];
public $attachOne = [];
public $attachMany = [];
} | <?php namespace Octommerce\Octommerce\Models;
use Model;
/**
* City Model
*/
class City extends Model
{
/**
* @var string The database table used by the model.
*/
public $table = 'octommerce_octommerce_cities';
/**
* @var array Guarded fields
*/
protected $guarded = ['*'];
/**
* @var array Fillable fields
*/
protected $fillable = [];
/**
* @var array Relations
*/
public $hasOne = [];
public $hasMany = [];
public $belongsTo = [
'state' => 'RainLab\Location\Models\State',
];
public $belongsToMany = [];
public $morphTo = [];
public $morphOne = [];
public $morphMany = [];
public $attachOne = [];
public $attachMany = [];
} |
Fix host and port for Heroku | import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager, Server
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.heroku import Heroku
# Initialize Application
app = Flask(__name__)
manager = Manager(app)
manager.add_command("runserver", Server(
host='0.0.0.0',
port = int(os.environ.get('PORT', 5000)),
use_debugger=True,
use_reloader=True)
)
heroku = Heroku()
app.config.from_object('config.Development')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
@app.route('/')
def test():
return "lala"
# Load Controllers
# Load Endpoints
# app.register_blueprint(users, url_prefix='/users')
#
heroku.init_app(app)
db.init_app(app)
#
# if __name__ == '__main__':
# port = int(os.environ.get('PORT', 5000))
# app.run(host='0.0.0.0', port=port, debug=True)
| import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager, Server
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.heroku import Heroku
# Initialize Application
app = Flask(__name__)
manager = Manager(app)
manager.add_command("runserver", Server(
use_debugger=True,
use_reloader=True)
)
heroku = Heroku()
app.config.from_object('config.Development')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
@app.route('/')
def test():
return "lala"
# Load Controllers
# Load Endpoints
# app.register_blueprint(users, url_prefix='/users')
#
heroku.init_app(app)
db.init_app(app)
#
# if __name__ == '__main__':
# port = int(os.environ.get('PORT', 5000))
# app.run(host='0.0.0.0', port=port, debug=True)
|
Use property function to define buffer | import Em from 'ember';
var get = Em.get;
var copy = Em.copy;
var ArrayPauser = Em.ArrayProxy.extend({
isPaused: false,
buffer: function () {
return Em.A();
}.property(),
addToBuffer: function (idx, removedCount, added) {
var buffer = get(this, 'buffer');
buffer.pushObject([idx, removedCount, added]);
},
clearBuffer: function () {
var buffer = get(this, 'buffer');
var arrangedContent = get(this, 'arrangedContent');
buffer.forEach(function (args) {
arrangedContent.replace(args[0], args[1], args[2]);
});
buffer.clear();
}.observes('isPaused'),
arrangedContent: function () {
var content = get(this, 'content');
var clone = copy(content);
return clone;
}.property('content'),
contentArrayDidChange: function (arr, idx, removedCount, addedCount) {
var added = arr.slice(idx, idx + addedCount);
var isPaused = get(this, 'isPaused');
var arrangedContent;
if (isPaused) {
this.addToBuffer(idx, removedCount, added);
}
else {
arrangedContent = get(this, 'arrangedContent');
arrangedContent.replace(idx, removedCount, added);
}
this.enumerableContentDidChange();
}
});
export default ArrayPauser;
| import Em from 'ember';
var get = Em.get;
var copy = Em.copy;
var ArrayPauser = Em.ArrayProxy.extend({
isPaused: false,
buffer: Em.A(),
addToBuffer: function (idx, removedCount, added) {
var buffer = get(this, 'buffer');
buffer.pushObject([idx, removedCount, added]);
},
clearBuffer: function () {
var buffer = get(this, 'buffer');
var arrangedContent = get(this, 'arrangedContent');
buffer.forEach(function (args) {
arrangedContent.replace(args[0], args[1], args[2]);
});
buffer.clear();
}.observes('isPaused'),
arrangedContent: function () {
var content = get(this, 'content');
var clone = copy(content);
return clone;
}.property('content'),
contentArrayDidChange: function (arr, idx, removedCount, addedCount) {
var added = arr.slice(idx, idx + addedCount);
var isPaused = get(this, 'isPaused');
var arrangedContent;
if (isPaused) {
this.addToBuffer(idx, removedCount, added);
}
else {
arrangedContent = get(this, 'arrangedContent');
arrangedContent.replace(idx, removedCount, added);
}
this.enumerableContentDidChange();
}
});
export default ArrayPauser;
|
Make pino output to stderr. | 'use strict';
const Promise = require('bluebird');
const pino = require('pino');
const forIn = require('lodash/forIn');
const Big = require('bignumber.js');
// Configure bluebird
// ----------------------------------------------------
// Make bluebird global
global.Promise = Promise;
// Improve debugging by enabling long stack traces.. it has minimal impact in production
Promise.config({ longStackTraces: true, warnings: false });
// Configure BigNumber
// ----------------------------------------------------
// Set BigNumber decimal places for a faster scoring
Big.config({ DECIMAL_PLACES: 16, ERRORS: false });
// Configure global logger (pino)
// ----------------------------------------------------
const logger = global.logger = pino(process.stderr);
const loggerPrototype = Object.getPrototypeOf(logger);
// Make sure that changing the level, affects all children
logger.children = {};
logger.child = (bindings) => {
const child = loggerPrototype.child.call(logger, bindings);
if (!bindings.module) {
throw new Error('Expected logger.child to have a module property');
}
logger.children[bindings.module] = child;
child.child = () => { throw new Error('Unable to use child() on a non-root logger'); };
return child;
};
Object.defineProperty(logger, 'level', {
get: loggerPrototype._getLevel,
set: (level) => {
loggerPrototype._setLevel.call(logger, level);
forIn(logger.children, (child) => { child.level = level; });
},
});
| 'use strict';
const Promise = require('bluebird');
const pino = require('pino');
const isPlainObject = require('lodash/isPlainObject');
const wrap = require('lodash/wrap');
const forIn = require('lodash/forIn');
const Big = require('bignumber.js');
// Configure bluebird
// ----------------------------------------------------
// Make bluebird global
global.Promise = Promise;
// Improve debugging by enabling long stack traces.. it has minimal impact in production
Promise.config({ longStackTraces: true, warnings: false });
// Configure BigNumber
// ----------------------------------------------------
// Set BigNumber decimal places for a faster scoring
Big.config({ DECIMAL_PLACES: 16, ERRORS: false });
// Configure global logger (pino)
// ----------------------------------------------------
const logger = global.logger = pino();
const loggerPrototype = Object.getPrototypeOf(logger);
// Make sure that changing the level, affects all children
logger.children = {};
logger.child = (bindings) => {
const child = loggerPrototype.child.call(logger, bindings);
if (!bindings.module) {
throw new Error('Expected logger.child to have a module property');
}
logger.children[bindings.module] = child;
child.child = () => { throw new Error('Unable to use child() on a non-root logger'); };
return child;
};
Object.defineProperty(logger, 'level', {
get: loggerPrototype._getLevel,
set: (level) => {
loggerPrototype._setLevel.call(logger, level);
forIn(logger.children, (child) => { child.level = level; });
},
});
|
[aeolus] Fix search results link issue | /**
* VIEW: Document Summary
*
*/
var template = require('./templates/documentHighlight.tpl');
module.exports = Backbone.Marionette.ItemView.extend({
//--------------------------------------
//+ PUBLIC PROPERTIES / CONSTANTS
//--------------------------------------
tagName: "li",
className: "clearfix",
template: template,
templateHelpers: function(){
var $projectData = $('body').data(),
baseUrl;
if ($projectData.editable){
baseUrl = aeolus.baseRoot + "/documents/" + this.docId;
} else {
baseUrl = aeolus.baseRoot + "/projects/" + $projectData.slug + "/comb?document_id=" + this.docId;
}
return {
pageURL: baseUrl
};
},
events: {
"click .go-to-result": "goToResult"
},
//--------------------------------------
//+ INHERITED / OVERRIDES
//--------------------------------------
initialize: function(options){
this.docId = options.documentId;
},
//--------------------------------------
//+ PUBLIC METHODS / GETTERS / SETTERS
//--------------------------------------
//--------------------------------------
//+ EVENT HANDLERS
//--------------------------------------
goToResult: function(event){
event.preventDefault();
window.location = eventst.currentTarget.href;
}
//--------------------------------------
//+ PRIVATE AND PROTECTED METHODS
//--------------------------------------
}); | /**
* VIEW: Document Summary
*
*/
var template = require('./templates/documentHighlight.tpl');
module.exports = Backbone.Marionette.ItemView.extend({
//--------------------------------------
//+ PUBLIC PROPERTIES / CONSTANTS
//--------------------------------------
tagName: "li",
className: "clearfix",
template: template,
templateHelpers: function(){
var $projectData = $('body').data(),
baseUrl;
if ($projectData.editable){
baseUrl = aeolus.baseRoot + "/documents/" + this.docId;
} else {
baseUrl = aeolus.baseRoot + "/projects/" + $projectData.slug + "/comb?document_id=" + this.docId;
}
return {
pageURL: baseUrl
};
},
events: {
"click .go-to-result": "goToResult"
},
//--------------------------------------
//+ INHERITED / OVERRIDES
//--------------------------------------
initialize: function(options){
this.docId = options.documentId;
},
//--------------------------------------
//+ PUBLIC METHODS / GETTERS / SETTERS
//--------------------------------------
//--------------------------------------
//+ EVENT HANDLERS
//--------------------------------------
goToResult: function(event){
event.preventDefault();
window.location = event.currentTarget.href;
window.location.reload();
}
//--------------------------------------
//+ PRIVATE AND PROTECTED METHODS
//--------------------------------------
}); |
Add space to legend text | export default {
lossLayer: {
// if we want to add this disclaimer (with the hover) to a widget in the legend,
// - type must be 'lossLayer' in the 'legend' section of the layer, OR
// - the layer has to have 'isLossLayer=true' in the metadata.
// For the second case (isLossLayer), type is being overwritten to 'lossLayer'
// in dataset-provider-actions#L56 (add more special here cases if needed)
statementPlain: 'Tree cover loss',
statementHighlight: ' is not always deforestation.',
tooltipDesc:
'Loss of tree cover may occur for many reasons, including deforestation, fire, and logging within the course of sustainable forestry operations. In sustainably managed forests, the “loss” will eventually show up as “gain”, as young trees get large enough to achieve canopy closure.',
},
isoLayer: {
statementPlain: 'This layer is only available for ',
statementHighlight: 'certain countries.',
},
lossDriverLayer: {
statementHighlight: 'Hover for details on drivers classes.',
tooltipDesc: `Commodity driven deforestation: Large-scale deforestation linked primarily to commercial agricultural expansion.\n
Shifting agriculture: Temporary loss or permanent deforestation due to small- and medium-scale agriculture.\n
Forestry: Temporary loss from plantation and natural forest harvesting, with some deforestation of primary forests.\n
Wildfire: Temporary loss, does not include fire clearing for agriculture.\n
Urbanization: Deforestation for expansion/intensification of urban centers.`,
},
};
| export default {
lossLayer: {
// if we want to add this disclaimer (with the hover) to a widget in the legend,
// - type must be 'lossLayer' in the 'legend' section of the layer, OR
// - the layer has to have 'isLossLayer=true' in the metadata.
// For the second case (isLossLayer), type is being overwritten to 'lossLayer'
// in dataset-provider-actions#L56 (add more special here cases if needed)
statementPlain: 'Tree cover loss',
statementHighlight: 'is not always deforestation.',
tooltipDesc:
'Loss of tree cover may occur for many reasons, including deforestation, fire, and logging within the course of sustainable forestry operations. In sustainably managed forests, the “loss” will eventually show up as “gain”, as young trees get large enough to achieve canopy closure.',
},
isoLayer: {
statementPlain: 'This layer is only available for ',
statementHighlight: 'certain countries.',
},
lossDriverLayer: {
statementHighlight: 'Hover for details on drivers classes.',
tooltipDesc: `Commodity driven deforestation: Large-scale deforestation linked primarily to commercial agricultural expansion.\n
Shifting agriculture: Temporary loss or permanent deforestation due to small- and medium-scale agriculture.\n
Forestry: Temporary loss from plantation and natural forest harvesting, with some deforestation of primary forests.\n
Wildfire: Temporary loss, does not include fire clearing for agriculture.\n
Urbanization: Deforestation for expansion/intensification of urban centers.`,
},
};
|
Print version on `-v | --version`
Closes #6 | var readJson = require('read-package-json');
var minimist = require('minimist');
var path = require('path');
var url = require('url');
var shields = require('../');
var argv = minimist(process.argv.slice(2), {
alias: {
v: 'version'
}
});
if (argv.version) {
console.log(require('../package.json').version);
return;
}
// no args
if (!argv._.length) {
var usage = [
'Shield generator for your current project.',
'',
'Usage:',
' shields [travis] [gemnasium]'
];
console.log(usage.join('\n'));
return;
}
var p = path.resolve('./package.json');
readJson(p, function(error, pkg) {
if (error) {
throw error;
}
var slug = url.parse(pkg.repository.url).path.slice(1);
var links = [''];
argv._.forEach(function(service) {
var shield = shields(slug, service);
var status = service === 'travis' ? 'Build' : 'Dependency';
console.log('[![' + status + ' Status][' + service + '-svg]][' + service + ']');
links.push(' [' + service + ']: ' + shield.link);
links.push(' [' + service + '-svg]: ' + shield.svg);
});
console.log(links.join('\n'));
}); | var readJson = require('read-package-json');
var minimist = require('minimist');
var path = require('path');
var url = require('url');
var shields = require('../');
var argv = minimist(process.argv.slice(2));
// no args
if (!argv._.length) {
var usage = [
'Shield generator for your current project.',
'',
'Usage:',
' shields [travis] [gemnasium]'
];
console.log(usage.join('\n'));
return;
}
var p = path.resolve('./package.json');
readJson(p, function(error, pkg) {
if (error) {
throw error;
}
var slug = url.parse(pkg.repository.url).path.slice(1);
var links = [''];
argv._.forEach(function(service) {
var shield = shields(slug, service);
var status = service === 'travis' ? 'Build' : 'Dependency';
console.log('[![' + status + ' Status][' + service + '-svg]][' + service + ']');
links.push(' [' + service + ']: ' + shield.link);
links.push(' [' + service + '-svg]: ' + shield.svg);
});
console.log(links.join('\n'));
}); |
Fix bug so that if the user fails to press change room the app does not break | //handles message function
var SubmitView = Backbone.View.extend({
events: {
'submit' : 'handleSubmit',
'change #lang' : 'changeLanguage',
'click #roomButton' : 'changeRoom'
},
initialize: function(){
this.currRoom = $("#room").val();
},
handleSubmit: function(e){
e.preventDefault();
if (this.currRoom === $("#room").val()) {
this.messageSubmitter();
} else {
this.changeRoom(e);
this.messageSubmitter();
}
},
messageSubmitter: function(){
var message = {
text: $('#chatInput').val(),
lang: $('#lang').val(),
username: $('#username').val(),
room: $('#room').val()
};
socket.emit('chat message', message);
$('#chatInput').val('');
},
changeLanguage: function(e){
e.preventDefault();
console.log('changing language');
socket.emit('change language', $('#lang').val());
},
changeRoom : function(e){
e.preventDefault();
this.currRoom = $("#room").val();
var lang = $('#lang').val();
socket.emit('join room', {room: this.currRoom, lang: lang});
}
});
| //handles message function
var SubmitView = Backbone.View.extend({
events: {
'submit' : 'handleSubmit',
'change #lang' : 'changeLanguage',
'click #roomButton' : 'changeRoom'
},
initialize: function(){},
handleSubmit: function(e){
e.preventDefault();
var message = {
text: $('#chatInput').val(),
lang: $('#lang').val(),
username: $('#username').val(),
room: $('#room').val()
};
socket.emit('chat message', message);
$('#chatInput').val('');
},
changeLanguage: function(e){
e.preventDefault();
console.log('changing language');
socket.emit('change language', $('#lang').val());
},
changeRoom : function(e){
e.preventDefault();
var room = $('#room').val();
var lang = $('#lang').val();
socket.emit('join room', {room: room, lang: lang});
}
});
|
Debug control flow and exit on errors | #! /usr/bin/python2
from os.path import expanduser,isfile
import sys
from urllib import urlopen
location_path="~/.location"
def location_from_homedir():
if isfile(expanduser(location_path)):
with open(expanduser(location_path)) as f:
return "&".join(f.read().split("\n"))
else:
print("no location file at ", location_path)
sys.exit(2)
def location_from_file(location_file):
try:
f = open(expanduser(location_file),'r')
except:
print("file ", location_file, " not found\nLooking in home directory")
return location_from_homedir()
if len(sys.argv) == 1:
# not given location file
data = location_from_homedir()
elif len(sys.argv) == 2:
# given location file
data = location_from_file(sys.argv[1])
else:
# wrong number of arguments
print("Usage: ", sys.argv[0], " [location file]")
sys.exit(1)
url="http://forecast.weather.gov/MapClick.php?"+data+"FcstType=digitalDWML"
forecast = urlopen(url).read()
| #! /usr/bin/python2
from os.path import expanduser,isfile
from sys import argv
from urllib import urlopen
location_path="~/.location"
def location_from_homedir():
if isfile(expanduser(location_path)):
with open(expanduser(location_path)) as f:
return "&".join(f.read().split("\n"))
else:
print("no location file at ", location_path)
def location_from_file(file):
try:
f = open(expanduser(file),'r')
except:
print("file ", location_file, " not found")
location_from_homedir
if len(argv) == 1:
# not given location file
data = location_from_homedir()
elif len(argv) == 2:
# given location file
data = location_from_file(argv[1])
else:
# wrong number of arguments
print("Usage: ", argv[0], " [location file]")
url="http://forecast.weather.gov/MapClick.php?"+data+"FcstType=digitalDWML"
forecast = urlopen(url).read()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.